LeetCode:面試題 02.01. 移除重複節點(C語言)

題目描述:
編寫代碼,移除未排序鏈表中的重複節點。保留最開始出現的節點。

示例1:

輸入:[1, 2, 3, 3, 2, 1]
輸出:[1, 2, 3]

示例2:

輸入:[1, 1, 1, 1, 2]
輸出:[1, 2]

提示:

鏈表長度在[0, 20000]範圍內。
鏈表元素在[0, 20000]範圍內。

進階:

如果不得使用臨時緩衝區,該怎麼解決?

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/remove-duplicate-node-lcci
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
解答:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* removeDuplicateNodes(struct ListNode* head)
{
    if (head == NULL) return NULL;
    
    struct ListNode *pre = head;

    while(NULL != pre)
    {
        struct ListNode *last = pre;

        while(NULL != last->next)
        {
            if(pre->val == last->next->val)
            {
                last->next = last->next->next;
            }
            else
            {
                last = last->next;
            }

        }
            pre = pre->next;
    }
    return head;
}

運行結果:
在這裏插入圖片描述

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