给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
第一种方法:迭代法
1、设置两个节点,记录上一个和当前节点;
2、设置一个临时节点记录当前节点的下一个节点;
3、先记录下一个节点,再将当前节点指向上一个节点;
4、把上一个节点更新为当前节点,再把当前节点变为下一个节点;
5、当当前节点为空时,返回上一个节点,即为反转后的头节点。
/**
* 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 prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}
第二种:递归法
递归的中间部分就是,中间节点的下一个节点的下一个节点是中间节点,即
head.next.next = head;
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next = null) {
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}
看不懂,背背背