存在一个按升序排列的链表,给你这个链表的头节点 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
- 题目数据保证链表已经按升序排列
代码实现(要在命令行运行噢)
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include <stdio.h>
#include <stdlib.h>
struct ListNode
{
int val;
struct ListNode* next;
};
struct ListNode* deleteDuplicates(struct ListNode* head)
{
struct ListNode dummy;
struct ListNode* p, * q, * prev;
prev = &dummy;
dummy.next = head;
p = q = head;
while (p != NULL)
{
while (q != NULL && q->val == p->val)
{
q = q->next;
}
if (p->next == q)
{
prev = p;
}
else
{
prev->next = q;
}
p = q;
}
return dummy.next;
}
int main(int argc, char** argv)
{
int i;
struct ListNode* head = NULL;
struct ListNode* prev = NULL;
struct ListNode* p;
for (i = 0; i < argc - 1; i++)
{
p = (struct ListNode*)malloc(sizeof(*p));
if (p == NULL)
{
return 0;
}
p->val = atoi(argv[i + 1]);
p->next = NULL;
if (head == NULL)
{
head = p;
prev = head;
}
else
{
prev->next = p;
prev = p;
}
}
p = deleteDuplicates(head);
while (p != NULL)
{
printf("%d ", p->val);
p = p->next;
}
printf("\n");
return 0;
}