题目:
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
输入:head = []
输出:[]
提示:
链表中节点的数目范围是 [0, 5000]
-5000 <= Node.val <= 5000
难度:
easy
代码:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = nullptr;
ListNode* cur = head;
while(cur)
{
ListNode* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};
思路:迭代
在链表的数据结构中,每个节点都只有指向后一个节点的指针,为了方便我们反转链表,我们需要添加一个指向前一个节点的指针,于是我们在遍历链表的同时,增加了指向前一个节点的指针pre并将其值设为每个节点的next来达到了反转链表的作用。
关于语句:ListNode* next = cur->next;
不仅简化了cur->next的写法,同时也提供了一个临时变量
不可省去。
最终return pre,得到的就是新的链表头。
更新
更新一个Java的解答:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur = head;
ListNode pre = null;
while(cur != null)
{
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}