struct Node* reverseList(struct Node *head) {
struct Node *p = head;
// 反转后的链表头部
struct Node *newListHead = NULL;
// 遍历链表
while (p != NULL) {
// 记录下一个结点
struct Node *temp = p->next;
// 使用头插法
// 当前结点的next指向新链表的头部
p->next = newListHead;
// 更新链表头部为当前结点
newListHead = p;
// 移动P
p = temp;
}
return newListHead;
}
struct Node* constructList(void) {
// 头结点
struct Node *head = NULL;
// 尾结点
struct Node *tail = NULL;
for (int i = 0; i < 5; i++) {
struct Node *node = (struct Node *)malloc(sizeof(struct Node));
node->data = I;
if (head == NULL) {
head = node;
} else {
tail->next = node;
}
tail = node;
}
tail->next = NULL;
return head;
}
void printList(struct Node *head) {
struct Node *temp = head;
while (temp != NULL) {
printf("node is %d\n", temp->data);
temp = temp->next;
}
}
![](https://img.haomeiwen.com/i5020103/aad0d8dadba38f76.png)
屏幕快照 2018-09-12 下午9.52.29.png
网友评论