206. Reverse Linked List

https://leetcode.com/problems/reverse-linked-list/

https://www.geeksforgeeks.org/reverse-a-linked-list/

/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

原地反转

考虑3个元素

1->2->3->null

进行反转的时候,一次操作2个元素。

1.先取出2个元素,current=1,next=2(也就是head.next);

2.先缓存next的next(也就是3), next2=3(也就是next.next)

3.next.next=current;   

4.current.next=null;  2->1->null

5.下一次操作取出2个元素,current=2,next=3.

6.需要一个while循环,判断next是否为null。重复执行(2,3,5),第4步只需要在while前面做一次就可以了,如果head.next不为空,就设置为空。

public ListNode ReverseList(ListNode head)
        {
            ListNode current = head;
            ListNode next = current?.next;
            if (next != null)
            {
                head.next = null;
            }
            while (next != null)
            {
                ListNode next2 = next.next;
                next.next = current;

                current = next;
                next = next2;
            }

            return current;
        }

 

posted @ 2019-02-22 13:16  ChuckLu  阅读(126)  评论(0编辑  收藏  举报