Reverse Linked List

Reverse a singly linked list.

 

/**
 * 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) {
        ListNode h = new ListNode(0);
        h.next = null;
        ListNode p = null;
        while(head!=null) {
            p = head.next;//记录head的后继
            head.next = h.next;
            h.next = head;
            head = p;
            if(p!=null)
            p = p.next;
        }
        return h.next;
    }
}

 

posted @ 2015-05-05 16:50  mrpod2g  阅读(64)  评论(0编辑  收藏  举报