Reverse Linked List
Java代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if(null == head || null == head.next)
return head;
ListNode last = head;
while(null != last.next)
last = last.next;
last.next = head;
ListNode tmp;
while(head.next != last){
tmp = head.next;
head.next = tmp.next;
tmp.next = last.next;
last.next = tmp;
}
head.next = null;
return last;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if(null == head || null == head.next)
return head;
ListNode last = head;
while(null != last.next)
last = last.next;
last.next = head;
ListNode tmp;
while(head.next != last){
tmp = head.next;
head.next = tmp.next;
tmp.next = last.next;
last.next = tmp;
}
head.next = null;
return last;
}
}