链表的头节点前插入一个节点
1、大家先看一下我自己出错的代码
#include<stdio.h>
#include<stdlib.h>
typedef struct student
{
int a;
struct student* next;
}S;
void insert(S *p,int a)
{
S* node = (S*)malloc(sizeof(S));
node->a = a;
node->next = p;
p = node;
}
void p1(S *p)
{
while (p != NULL)
{
printf("%d", p->a);
p = p->next;
}
}
int main()
{
S s1 = { 2,NULL };
S s2 = { 3,NULL };
S s3 = { 4,NULL };
S *head = &s1;
s1.next = &s2;
s2.next = &s3;
S* p = head;
insert(p,5);
p1(p);
return 0;
}
上面的这个代码意思就是在头结点前再加入一个节点但方法是错的
2、其实上面的问题是头指针的位置就没变
3、那么现在大家可以想一个问题就是在向交换两个数的函数里面传入两个数如果不加地址符号,那么在main函数里两个数就不会变位置
4、所以方法很简单就是来个双指针
#include<stdio.h>
#include<stdlib.h>
typedef struct student
{
int a;
struct student* next;
}S;
void insert(S **p,int a)
{
S* node = (S*)malloc(sizeof(S));
node->a = a;
node->next = *p;
*p = node;
}
int main()
{
S s1 = { 2,NULL };
S s2 = { 3,NULL };
S s3 = { 4,NULL };
S *head = &s1;
s1.next = &s2;
s2.next = &s3;
S* p = head;
insert(&p,5);
while (p != NULL)
{
printf("%d\n", p->a);
p = p->next;
}
return 0;
}
上面的代码就是做了一点小改动,这个就可以实现我们的目的了,希望能帮到你。