1. 关键点
- 结点定义
//Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
核心: 逆序思想
参考:https://blog.csdn.net/lycnjupt/article/details/47103433
循环过程如下:
next = head->next;
head->next = prev;
prev = head;
head = next;
初始条件为“` prev = NULL;
迭代停止条件为 head == NULL
2. 创建链表
ListNode* create()
{
ListNode* pHead, *pNode, *temp;
int x;
pHead = pNode = (ListNode*)malloc(sizeof(ListNode)); //带头节点的链表
// 先把第一个结点做了。
printf("请输入链表数据,以小于0 的为结束标志:\n");
scanf("%d", &x);
pNode->val = x;
pNode->next = NULL;
scanf("%d", &x);
while (x>=0)
{
temp = (ListNode*)malloc(sizeof(ListNode));
temp->val = x;
temp->next = NULL;
pNode->next = temp;//上一个结点指向当前新创建的结点
pNode = temp;
scanf("%d", &x);
}
pNode->next = nullptr;
return