Reverse a singly linked list.
Iterative 解法:四步反转法。
/**
* 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 dummpy = new ListNode(-1);
dummpy.next = head;
ListNode cur = dummpy.next;
while(cur != null && cur.next != null) {
ListNode curnext = cur.next;
cur.next = curnext.next;
curnext.next = dummpy.next;
dummpy.next = curnext;
}
return dummpy.next;
}
}
Recursion 写法:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode newhead = reverseList(head.next);
head.next = null;
ListNode node = newhead;
// go to the last node;
while(node!=null && node.next != null) {
node = node.next;
}
node.next = head;
return newhead;
}
}