206. Reverse Linked List #
题目 #
给定单链表头节点head
,反转并返回反转后的链表。
思路 #
代码 #
递归 #
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 newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}
迭代 #
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, cur = head, next = head.next;
while (cur != null) {
cur.next = prev;
prev = cur;
cur = next;
if (next != null) next = next.next;
}
return prev;
}
}