给定一个已排序的链表的头head,删除原始链表中所有重复数字的节点,只留下不同的数字,返回已排序的链表。
示例1:
输入:head = [1,2,3,3,4,4,5] 输出:[1,2,5]示例2:
输入:head = [1,1,1,2,3] 输出:[2,3]提示:
- 链表中节点数目在范围
[0, 300]内-100 <= Node.val <= 100- 题目数据保证链表已经按升序 排列
解题方案:一次遍历
- 给定的链表是排好序的,因此重复的元素在链表中出现的位置是连续的。
- 链表的头节点可能会被删除,因此需要额外使用一个哑节点(dummy node)指向链表头节点。
- 从指针cur指向链表的哑节点。
- 如果当前cur.next与cur.next.next对应元素相同,需要将cur.next以及所有后面拥有相同元素值的链表节点全部删除。
- 记下该元素值x,随后不断将cur.next从链表中移除,直到cur.next为空节点或其元素值不等于x为止。
- 将链表所有元素值为x的节点全部删除。
struct ListNode* deleteDuplicates(struct ListNode* head) { if(!head) return head; struct ListNode* dummy = malloc(sizeof(struct ListNode)); dummy->next = head; struct ListNode* cur = dummy; while(cur->next && cur->next->next) { if(cur->next->val == cur->next->next->val) { int x=cur->next->val; while(cur->next && cur->next->val ==x) cur->next = cur->next->next; } else cur = cur ->next; } return dummy->next; }

1709

被折叠的 条评论
为什么被折叠?



