【Leetcode-Easy-206】Reverse Linked List

【Leetcode-Easy-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; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) return head;

        ListNode first = head;
        first.next = null;
        ListNode second = head.next;

        while (second != null){
            ListNode tempNode = second.next;
            second.next = first;
            first = second;
            second = tempNode;
        }
        return first;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章