[java]反转单项链表,用O(n)时间和O(1)空间

链表数据结构

public class ListNode {
    public int val;
    public ListNode next;
    public ListNode(int x) {
        val = x;
    }
}

反转代码

public ListNode reverse(ListNode head) {
    ListNode p;
    ListNode tmp = head.next;
    head.next = null;
    while(tmp != null) {
        p = tmp;
        tmp = tmp.next;
        p.next = head;
        head = p;
    }
    return head;
}

 

posted on 2015-07-13 11:06  _dshizhh  阅读(359)  评论(0)    收藏  举报

导航