-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsingly_linked.c
62 lines (52 loc) · 994 Bytes
/
singly_linked.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <stdio.h>
#include <stdlib.h>
// 定义节点结构体
struct Node
{
int data;
struct Node *next;
};
// 打印链表
void printList(struct Node *head)
{
struct Node *temp = head;
while (temp != NULL)
{
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
// 插入新节点到链表尾部
void appendNode(struct Node **head, int data)
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
struct Node *last = *head;
newNode->data = data;
newNode->next = NULL;
if (*head == NULL)
{
*head = newNode;
return;
}
while (last->next != NULL)
{
last = last->next;
}
last->next = newNode;
}
int main()
{
struct Node *head = NULL;
// 插入节点
appendNode(&head, 1);
appendNode(&head, 2);
appendNode(&head, 3);
printList(head); // 输出:1 -> 2 -> 3 -> NULL
return 0;
}
/*
jarry@MacBook-Pro linked % gcc singly_linked.c
jarry@MacBook-Pro linked % ./a.out
1 -> 2 -> 3 -> NULL
*/