Reverse Linked List

Reverse Linked List


Reverse a singly 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;
        
    }
}

 


版权声明:本文为shuitawuhen原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。