题解 | #反转链表#
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
大致思路
work指针指向当前即将成为头结点的指针,然后让p指向该节点的next(注意,该节点只是即将成为头结点,而不是已经成为头结点)
当work插到头了之后,让head指向该节点(即head一直指向新链表的表头),此时p指向着原链表的剩余链表的头位置,然后又让work指向p,p指向work的next,继续处理work,循环直至work为空,最后返回head。
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode ReverseList(ListNode head) { if (head == null || head.next == null) { return head; } ListNode work = head.next; head.next = null; ListNode p; while (work != null) { p = work.next; work.next = head; head = work; work = p; if (work != null) { p = work.next; } } return head; } }