【LeetCode-206】反转链表

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) { // [1,2,3,4,5]
        ListNode prev = null;
        while(head != null){
            ListNode next = head.next; //2
            head.next = prev; //1->NULL
            prev = head; //prev = 1
            head = next; // 2转为第一个结点
            //第一个while循环结束,有:2->1->NULL
        }
        return prev;
    }
}

 

posted @ 2020-04-16 22:23  CodeCorner  阅读(78)  评论(0)    收藏  举报