当前位置:   article > 正文

链表修改数据(附完整代码)_如何修改链表中的数据

如何修改链表中的数据

(完整代码在文章 "最…下方")

  1. 创建链表并初始化值

  1. 修改链表中指定位置数据

  1. 遍历输出链表查看结果

(下方为头部代码)

  1. //定义结构体
  2. typedef struct Node{
  3. int data;            //数据域
  4. struct Node *next;    //指针域
  5. }Node;
  6. void create(Node *head);    //创建
  7. void alter(Node *head);    //修改
  8. void print(Node *head);     //输出
  9. int main(){
  10. Node *head = (Node *)malloc(sizeof(Node));
  11. create(head);        //创建链表
  12. alter(head); //修改链表指定位置的值
  13. print(head);        //遍历链表
  14. }

1、创建链表

  1. void create(Node *head){
  2. if(!head){
  3. return;
  4. }
  5. Node *q = head;
  6. for(int i=0;i<5;i++){
  7. Node *p = (Node *)malloc(sizeof(Node));
  8. p->data = i+1;
  9. q->next = p;
  10. q = q->next;
  11. }
  12. q->next = NULL;
  13. }

2、修改数据

这里将for循环 与 while循环 两种方式均展示出来。

  1. void alter(Node *head){
  2. if(!head){
  3. return;
  4. }
  5. Node *q = head;
  6.     // for循环修改值
  7. for(int i=0; q->next; i++, q=q->next ){
  8. if(i==3){
  9. printf("请输入修改后的值:");
  10. scanf("%d",&q->data);
  11. }
  12. }
  13.     // while循环修改值
  14.     int count = 0;        //定义计数器,用来统计循环次数 即结点位置
  15.     while(q->next){
  16.         count++;
  17.         if(count ==3){
  18.             printf("请输入修改后的值:");
  19. scanf("%d",&q->data);
  20.         }
  21.     }
  22. }

3、遍历链表

  1. void print(Node *head){
  2. if(!head) {
  3. return;
  4. }
  5. Node *q = head->next;
  6. while(q){
  7. printf("%d ",q->data);
  8. q = q->next;
  9. }
  10. }

  • 完整代码板

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. typedef struct Node{
  4. int data;
  5. struct Node *next;
  6. }Node;
  7. void create(Node *head);
  8. void alter(Node *head);
  9. void print(Node *head);
  10. int main(){
  11. Node *head = (Node *)malloc(sizeof(Node)) ;
  12. create(head);
  13. alter(head);
  14. print(head);
  15. }
  16. void create(Node *head){
  17. if(!head){
  18. return;
  19. }
  20. Node *q = head;
  21. for(int i=0;i<5;i++){
  22. Node *p = (Node *)malloc(sizeof(Node));
  23. p->data = i+1;
  24. q->next = p;
  25. q = q->next;
  26. }
  27. q->next = NULL;
  28. }
  29. void alter(Node *head){
  30. if(!head){
  31. return;
  32. }
  33. Node *q = head;
  34. for(int i=0; q->next; i++, q=q->next ){
  35. if(i==3){
  36. printf("请输入修改后的值:");
  37. scanf("%d",&q->data);
  38. }
  39. }
  40. }
  41. void print(Node *head){
  42. if(!head) {
  43. return;
  44. }
  45. Node *q = head->next;
  46. while(q){
  47. printf("%d ",q->data);
  48. q = q->next;
  49. }
  50. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/55354
推荐阅读
相关标签
  

闽ICP备14008679号