当前位置:   article > 正文

数据结构 | 头插法创建单链表、遍历链表、删除链表 | C语言代码_输入一系列自然数(0和正整数),输入-1时表示输入结束。按照输入的顺序,用头插法建

输入一系列自然数(0和正整数),输入-1时表示输入结束。按照输入的顺序,用头插法建

题目:

        输入一系列自然数(0和正整数),输入-1时表示输入结束。按照输入的顺序,用头插法建立单链表,并遍历所建立的单链表,输出这些数据。注意 -1 不加入链表。

输入格式:

        第一行是一个正整数k,表示以下会有k组测试数据

        每组测试数据是一系列以空格隔开的自然数(0和正整数)。数列末尾的 -1 表示本组测试数据结束。按照输入的顺序,用头插法建立单链表,并遍历所建立的单链表,输出这些数据。注意 -1 不加入链表。

输出格式:

        对于每组测试数据,输出链表中各节点的数据域。每个数据后有一个空格。每组测试数据的输出占1行。

输入样例:

3

1 2 3 4 5 -1

30 20 10 -1

4 2 2 1 1 2 0 2 -1

输出样例:

5 4 3 2 1

10 20 30

2 0 2 1 1 2 2 4

代码:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. // 定义单链表节点结构
  4. struct Node {
  5. int data; // 数据域
  6. struct Node* next; // 指针域
  7. };
  8. // 创建链表的函数
  9. struct Node* createLinkedList() {
  10. struct Node* head = NULL;
  11. int value;
  12. // 输入链表元素
  13. while (1) {
  14. scanf("%d", &value);
  15. // 判断是否插入节点
  16. if (value == -1) {
  17. break;
  18. }
  19. // 头插法
  20. struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
  21. newNode->data = value;
  22. newNode->next = head;
  23. head = newNode;
  24. }
  25. return head;
  26. }
  27. // 遍历链表
  28. void traverseAndPrint(struct Node* head) {
  29. struct Node* current = head;
  30. while (current != NULL) {
  31. printf("%d ", current->data);
  32. current = current->next;
  33. }
  34. printf("\n");
  35. }
  36. // 删除链表释放内存
  37. void deleteLinkedList(struct Node* head) {
  38. struct Node* current = head;
  39. while (current != NULL) {
  40. struct Node* temp = current;
  41. current = current->next;
  42. free(temp);
  43. }
  44. }
  45. int main() {
  46. // 输入链表节点个数
  47. int k;
  48. scanf("%d", &k);
  49. // 输入元素
  50. for (int i = 0; i < k; i++) {
  51. struct Node* head = createLinkedList();
  52. traverseAndPrint(head);
  53. deleteLinkedList(head);
  54. }
  55. return 0;
  56. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/438841
推荐阅读
相关标签
  

闽ICP备14008679号