iT邦幫忙

第 11 屆 iT 邦幫忙鐵人賽

DAY 25
0

題目:

https://leetcode.com/problems/reverse-linked-list/
翻轉串結鏈結並回傳。

解題思路:

透過三個指標post、pre、cur紀錄位置,一開始post等於首位置當此不為空時pre位置等於cur位置,cur位置等於post現在位置,將post移至下一個位置然而將cur指標指向pre達到反轉效果,直到條件不符合為止。

C版本:

struct ListNode* reverseList(struct ListNode* head) {
    struct ListNode* post = head;
    struct ListNode* pre = NULL;
    struct ListNode* cur = NULL;
    
    while(post != NULL)
    {
        pre = cur;
        cur = post;
        post = post -> next;
        cur -> next =pre;
    }
    
    return cur;
}

Javascript版本:

var reverseList = function(head) {
    var post = head;
    var pre = null;
    var cur = null;
    
    while(post != null)
    {
        pre = cur;
        cur = post;
        post = post.next;
        cur.next = pre; 
    }
    return cur;
};

程式Github分享:

https://github.com/SIAOYUCHEN/leetcode

相似主題分享:

https://ithelp.ithome.com.tw/users/20100009/ironman/2500
https://ithelp.ithome.com.tw/users/20113393/ironman/2169
https://ithelp.ithome.com.tw/users/20107480/ironman/2435
https://ithelp.ithome.com.tw/users/20107195/ironman/2382
https://ithelp.ithome.com.tw/users/20119871/ironman/2210
https://ithelp.ithome.com.tw/users/20106426/ironman/2136

本日分享:

In order not to leave regrets in life, we should catch every opportunity to change our lives as much as possible.
為了不讓生活留下遺憾和後悔,我們應該儘可能抓住一切改變生活的機會


上一篇
DAY24 Intersection of Two Linked Lists
下一篇
DAY26 Remove Linked List Elements
系列文
刷題記錄與人生分享34

尚未有邦友留言

立即登入留言