Reverse Linked List

///  實現鏈表反轉的兩種方法


///  1. 創建新鏈表


struct ListNode* reverseList(struct ListNode* head) {
    if(head == NULL) return NULL;
    struct ListNode* nlist = NULL;
    for(struct ListNode* p = head;p;){
        struct ListNode* temp = p->next;
        p->next = nlist;
        nlist = p;
        p = temp;
    }
    return nlist;

}


/// 2 . 移動cur / head指針指向

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

}

發佈了91 篇原創文章 · 獲贊 6 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章