[leedcode 206] 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) {
        //需要画图,注意每个节点的起始位置,注意第一个rear为null
        if(head==null||head.next==null) return head;
        ListNode rear=null;
        ListNode p=head;
        ListNode pre=head;
        while(pre!=null){
            pre=pre.next;
            p.next=rear;
            rear=p;
            p=pre;
        }
        return rear;
        
    }
}

 

posted @ 2015-08-03 22:38  ~每天进步一点点~  阅读(142)  评论(0编辑  收藏  举报