题目描述:
Reverse a singly linked list.
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
思路一:
迭代
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null)
return null;
ListNode newHead = null;
while (head != null)
{
ListNode next = head.next;
head.next = newHead;
newHead = head;
head = next;
}
return newHead;
}
}
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode pivot = head;
ListNode frontier = null;
while (pivot != null && pivot.next != null)
{
frontier = pivot.next;
pivot.next = pivot.next.next;
frontier.next = head;
head = frontier;
}
return head;
}
}
思路二:
递归
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null)
return null;
ListNode newHead = null;
return helper(head, newHead);
}
private ListNode helper(ListNode head, ListNode newHead)
{
if (head == null)
return newHead;
ListNode next = head.next;
head.next = newHead;
return helper(next, head);
}
}
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode nextNode = head.next;
ListNode newHead = reverseList(nextNode);
nextNode.next = head;
head.next = null;
return newHead;
}
}