链表的头指针和头结点
如题,头指针需要二级指针,二级指针的用法,请求大神给实例
给楼主解难来啦!!!!!!!!!!!!!
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
void exchange(struct node **root) //通过二级指针传参修改链表的头
{
struct node *new = NULL, *head = NULL;
head = *root;
// printf("head in exchange = %p\n",head);
new = (struct node *)malloc(sizeof(struct node));
new->data = 10;
new->next = head->next;
*root = new;
// printf("head = %d\n",head->data);
}
int main(void)
{
struct node *head = NULL;
struct node *tail = NULL, *new = NULL;
int n;
for(n = 1;n < 6; n++) //建立链表
{
new = (struct node *)malloc(sizeof(struct node));
new->data = n;
new->next = NULL;
if(NULL == head)
{
head = new;
continue;
}
for(tail = head; tail->next != NULL; tail = tail->next)
;
tail->next = new;
}
for(tail = head; tail != NULL; tail = tail->next) //修改前打印链表
{
printf("%d ",tail->data);
}
printf("\n");
struct node **root = &head; //给二级指针赋值
// printf("head in main %p\n",head);
exchange(root);
for(tail = head; tail != NULL; tail = tail->next) //修改后打印链表
{
printf("%d ",tail->data);
}
printf("\n");
for(tail = head; tail != NULL; tail = new) //free链表
{
new = tail->next;
free(tail);
}
return 0;
}