c语言节点怎么删除文件,1771: [编程入门]链表之节点删除(C语言)

解题思路:

首先,需要创建一个链表typedef struct student {

int id;

int chengji;

struct student* next;

}*node, Node;

//一般创建链表我们都用typedef  struct,因为这样定义结构体变量时,

//我们就可以直接可以用node a 来定义结构体指针,Node b来定义结构体变量

//其实就是用 node 代替了struct student *

//Node 代替了struct student

其次初始化一个链表,n为链表节点个数。node creat(int n)

{

node head, p, q;

head = (node)malloc(sizeof(Node));

head->next = NULL;

q = head;

for (int i = 0; i 

{

p = (node)malloc(sizeof(Node));

scanf("%d%d", &(*p).id, &p->chengji);

p->next = q->next; //这里用的链表的后插法

q->next = p;

q = p;

}

return head;

}

之后是进行删除void fun(node h1, node h2)

{

h2 = h2->next;

node p, t = h2;

while (h1->next != NULL)

{

h2 = t;

int flag = 0;

while (h2 != NULL)

{

p = (node)malloc(sizeof(Node));

if (h1->next->id == h2->id)

{

p = h1->next;

h1->next = p->next;

free(p);

flag = 1;

}

h2 = h2->next;

}

if(flag == 0)    //重点!

h1 = h1->next;   //重点!

}

}

这里有一个重点,就是如果进行了删除,是不需要进行指向下一个链表的,

因为h1之前指向的next已经被删除了,现在指向的next应该是之前的next

的next,所以不需要再往后移动了

最后进行打印void outPut(node h1)

{

int count = 0;

node p = h1;

while (h1 = h1->next) count++;

printf("%d\n", count);

p = p->next;

while (p != NULL)

{

printf("%d %d\n", p->id, p->chengji);

p = p->next;

}

}

参考代码:#include 

#include 

typedef struct student {

int id;

int chengji;

struct student* next;

}*node, Node;

node creat(int n)

{

node head, p, q;

head = (node)malloc(sizeof(Node));

head->next = NULL;

q = head;

for (int i = 0; i 

{

p = (node)malloc(sizeof(Node));

scanf("%d%d", &(*p).id, &p->chengji);

p->next = q->next;

q->next = p;

q = p;

}

return head;

}

void fun(node h1, node h2)

{

h2 = h2->next;

node p, t = h2;

while (h1->next != NULL)

{

h2 = t;

int flag = 0;

while (h2 != NULL)

{

p = (node)malloc(sizeof(Node));

if (h1->next->id == h2->id)

{

p = h1->next;

h1->next = p->next;

free(p);

flag = 1;

}

h2 = h2->next;

}

if(flag == 0)

h1 = h1->next;

}

}

void outPut(node h1)

{

int count = 0;

node p = h1;

while (h1 = h1->next) count++;

printf("%d\n", count);

p = p->next;

while (p != NULL)

{

printf("%d %d\n", p->id, p->chengji);

p = p->next;

}

}

int main()

{

int m, n;

node head1, head2;

scanf("%d%d", &n, &m);

head1 = creat(n);

head2 = creat(m);

fun(head1, head2);

outPut(head1);

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值