给你单链表的头节点head
,请你反转链表,并返回反转后的链表
效果如图所示
- 迭代方式
/**
* 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) {
if(head == null){
return head;
}
ListNode curr = head;
ListNode pre = null;
ListNode last;
while(curr != null && curr.next != null){
last = curr.next; // 保留下一个节点
curr.next = pre; // 将当前节点的下一节点赋值为上一节点
pre = curr; // 更新上一节点的值
curr = last; // 更新当前节点
}
curr.next = pre;
return curr;
}
}
- 递归方式
/**
* 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) {
if(head == null || head.next == null){
return head;
}
ListNode new_head = reverseList(head.next);
// 想象一下,当递归到head为第四个节点时,需要变动第五个节点的下一节点是当前这个第四节点
head.next.next = head; // 给下一节点的属性next赋值
head.next = null; // 第四节点的属性next需要修改,这里修改为null,从而第三节点会再次修改一遍 head.next.next = head; //当head为第三节点的时候...等到了 head 为第一节点的时候,这时第一节点的next为null,对吧?
return new_head;
}
}