1.题目描述
[206] 反转链表
https://leetcode-cn.com/problems/reverse-linked-list/description/
algorithms
Easy (59.78%)
Total Accepted: 51.7K
Total Submissions: 85.6K
Testcase Example: ‘[1,2,3,4,5]’
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
2.解答
在遍历列表时,将当前节点的 next
指针改为指向前一个元素。由于节点没有引用其上一个节点,因此必须事先存储其前一个元素。在更改引用之前,还需要另一个指针来存储下一个节点。不要忘记在最后返回新的头引用!
C语言代码:
struct ListNode* reverseList(struct ListNode* head) {
if (head == NULL) {
return NULL;
}
if (head->next == NULL) {
return head;
}
if (head->next->next == NULL) {
struct ListNode* c = head->next;
c->next = head;
head->next = NULL;
return c;
}
struct ListNode* p = head;
struct ListNode* c = p->next;
struct ListNode* n = c->next;
p->next = NULL;
while(n){
c->next = p;
p = c;
c = n;
n = n->next;
}
c->next = p;
return c;
}
对比一下别人的代码,呜呜呜哭晕。其实n (next) 指针可看作是临时的变量,目的只是为了移动c (cur) 指针,另外,将p (pre) 初始指向NULL,c (cur) 依次指向链表结点,更好 一些,下面的代码无需考虑链表长度,代码是通用的。
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* pre = NULL;
struct ListNode* cur;
struct ListNode* tmp;
cur = head;
while(cur){
tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
return pre;
}