首页 > 代码库 > leetcode Remove Duplicates from Sorted List

leetcode Remove Duplicates from Sorted List

给定一个链表,去除重复的值,每个数字只出现一次,例如

Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

思路:

用pre记录合法链表的最后一个,now为第二个节点一直往后走,如果now的值不等于pre那么更新pre为now,now继续往后走,最后记得将pre的next置为空。

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *deleteDuplicates(ListNode *head) {        if (head == NULL || head -> next == NULL) return head;        ListNode *ans = head;        ListNode *pre = ans;        ListNode *now = head -> next;        while(now)        {            if (now -> val == pre -> val)                now = now -> next;            else            {                pre -> next = now;                pre = now;                now = now -> next;            }        }        pre -> next = NULL; // 这个不能忘        return ans;    }};

 

leetcode Remove Duplicates from Sorted List