【Lintcode】35. Reverse Linked List

題目地址:

https://www.lintcode.com/problem/reverse-linked-list/description

翻轉鏈表。只需注意用頭插法轉移node的時候要緩存一下下一個節點即可。代碼如下:

public class Solution {
    /**
     * @param head: n
     * @return: The new head of reversed linked list.
     */
    public ListNode reverse(ListNode head) {
        // write your code here
        ListNode res = null;
        while (head != null) {
            ListNode tmp = head.next;
            head.next = res;
            res = head;
            head = tmp;
        }
        
        return res;
    }
}

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

時間複雜度O(n)O(n),空間O(1)O(1)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章