Leetcode #206 反轉鏈表
題目描述:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
迭代解法:
假設有一個鏈表,1→2→3→4,那麼反轉之後得到的鏈表應該是4→3→2→1,
這裡,用 pre 來存取反轉之後的節點,
首先,傳入值為1的節點,那麼,1的下一個指向應該是null,
接著,傳入值為2的節點,那麼,2的下一個指向就是1,
像這樣,依次類推,直到遍歷到最後一個節點,
head.next = pre; pre = head; 這兩行就是實現了上述反轉的操作,
為了不斷鏈並能繼續訪問下一個節點,需要先用next保存下一個節點的值,即next = head.next;,
當反轉操作結束後,再將該賦賦給head,即head = next;。
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} head * @return {ListNode} */ var reverseList = function(head) { let next = null, pre = null; while (head) { next = head.next; head.next = pre; pre = head; head = next; } return pre; };
題目連結:https://leetcode-cn.com/problems/reverse-linked-list/description/

Vance
0
Tags :