C语言
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
struct ListNode
*pre = NULL,
*cur = NULL,
*tail = NULL,
*next = NULL;
cur = head;
while (cur != NULL) {
tail = cur->next;
if (tail == NULL) {
cur->next = pre;
pre = cur;
break;
}
next = tail->next;
cur->next = pre;
tail->next = cur;
pre = tail;
cur = next;
}
return pre;
}
注意点
- 当
cur->next == NULL
即tail
为空时,应该注意cur
与pre
节点的链接避免遗漏最后这个cur
节点;