链表以及指针相关
#include<stdio.h> #include<stdlib.h> //定义结构体Node,链表结点 struct Node { int data; struct Node *next; }; //新建一个节点 struct Node * createNode( int data) { struct Node * node= (struct Node *)malloc( sizeof(struct Node)); node->data=data; return node; } /* //新建一个带头结点的空链表,返回头指针 struct Node * createLink() { struct Node *head= (struct Node *)malloc( sizeof(struct Node)); head->next=0; return head; } */ //新建一个带头结点的空链表 void createLink( struct Node **head) { *head= (struct Node *)malloc( sizeof(struct Node)); (*head)->next=0; } //把一个结点加入到链表中 void addLinkNode(struct Node *head,struct Node *node ) { node->next=head->next; head->next=node; } //输出链表中的结点数据 void printData(struct Node *head) { struct Node *node; node=head->next; while (node) { printf("%d\n",node->data); node=node->next; } }
//删除一个节点 void deleteLinkNode (struct Node *head,int data) { struct Node *node,*delnode; node=head; while(node->next) { if((node->next)->data==data) { delnode=node->next; node->next=delnode->next; free (delnode); } else node=node->next; } }
int main(){ struct Node *link=0; int i; //link=createLink();// createLink(&link);// for(i=0;i<9;i++) { struct Node *node=createNode(i); addLinkNode(link, node); } printData(link); getchar(); return 0; }
几个问题:
1.关于创建链表,如果想把链表的头指针通过参数的方式传递给子函数,而且通过createLink的形参改变实参,以下的代码是无效的。虽然head是指针,但是传递过来的是他自身的内容,即一个Node的地址,而不是其自身的地址,这样形参head虽然改变,但是实参link却不会变化。
void createLink( struct Node *head) { head= (struct Node *)malloc( sizeof(struct Node)); head->next=0; } struct Node *link=0; createLink(link);
所以,想要通过这种方式获得头指针,需要把保存头指针地址的link的地址作为实参传递给传递给子函数,link 的地址为&link,很明显createLink的形参也要改变类型,变为struct Node **head,代码如下:
void createLink( struct Node **head) { *head=(struct Node *)malloc( sizeof(struct Node)); (*head)->next=0; } struct Node *link=0; createLink(&link);
2.&link是获取的link的地址,很明显结果为一个常量。