发布时间:2020-09-29 10:05 原文链接: 超详细的单链表学习教程(一)

一、单链表的遍历

1、什么叫遍历?

遍历就是把单链表中的各个节点挨个拿出来,就叫遍历。

2、如何来遍历单链表?

从头指针+头节点开始,顺着链表挂接指针依次访问链表的各个节点,取出这个节点的数据,然后再往下一个节点,直到最后一个节点,结束访问。

3、注意事项:

一是不能遗漏元素,二是不能重复、追求效率

4、实战代码演示:

1 #include <stdio.h>

2 #include <strings.h>

3 #include <stdlib.h>

4// 构建一个链表的节点

5struct node

6 {

7    int data;                               // 有效数据

8     struct node *pNext;             // 指向下一个节点的指针

9  };

10  // 作用:创建一个链表节点

11 // 返回值:指针,指针指向我们本函数新创建的一个节点的首地址

12 struct node * create_node(int data)

13 {

14    struct node *p = (struct node *)malloc(sizeof(struct node));

15    if (NULL == p)

16    {

17            printf("malloc error.n");

18            return NULL;

19    }

20    // 清理申请到的堆内存

21    bzero(p, sizeof(struct node));

22    // 填充节点

23    p->data = data;

24    p->pNext = NULL;

25    return p;

26}

27// 计算添加了新的节点后总共有多少个节点,然后把这个数写进头节点中。

28void insert_tail(struct node *pH, struct node *new)

29{

30    int cnt = 0;

31    // 分两步来完成插入

32    // 第一步,先找到链表中最后一个节点

33    struct node *p = pH;

34    while (NULL != p->pNext)

35    {

36            p = p->pNext;                // 往后走一个节点

37            cnt++;

38    }

39    // 第二步,将新节点插入到最后一个节点尾部

40    p->pNext = new;

41    pH->data = cnt + 1;

42 }

43 void insert_head(struct node *pH, struct node *new)

44 {

45    // 第1步: 新节点的next指向原来的第一个节点

46      new->pNext = pH->pNext;

47    // 第2步: 头节点的next指向新节点的地址

48       pH->pNext = new;

49    // 第3步: 头节点中的计数要加1

50    pH->data += 1;

51 }

52 // 遍历单链表,pH为指向单链表的头指针,遍历的节点数据打印出来

53 void bianli(struct node*pH)

54 {

55    //pH->data  // 头节点数据,不是链表的常规数据,不要算进去了

56    //struct node *p = pH;   // 错误,因为头指针后面是头节点

57    struct node *p = pH->pNext;     // p直接走到第一个节点

58    printf("-----------开始遍历-----------n");

59    // 是不是最后一个节点

60    while (NULL != p->pNext)

61    {

62            printf("node data: %d.n", p->data);

63            p = p->pNext;

64            // 走到下一个节点,也就是循环增量

65    }

66    printf("node data: %d.n", p->data);

67    printf("-------------完了-------------n");

68 }

69int main(void)

70{

71    // 定义头指针

72    //struct node *pHeader = NULL;

73    // 这样直接insert_tail会段错误。

74    struct node *pHeader = create_node(0);

75    insert_head(pHeader, create_node(11));

76    insert_head(pHeader, create_node(12));

77    insert_head(pHeader, create_node(13));

78    // 访问链表头节点的有效数据

79    printf("beader node data: %d.n", pHeader->data);

80    bianli(pHeader);

81    return 0;

82 }