参考:https://blog.csdn.net/ABABC1234/article/details/131329837
删除有序链表中重复的元素,比如
输入链表1,2,2,3,3,4。输出链表1,4
输入链表1,1,2,3,4,4,输出链表2,3
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node, *LinkedList;
// 创建一个新节点
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Error! Unable to create a new node.\n");
exit(0);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 在链表末尾添加新节点
void append(LinkedList* head, int data) {
if (*head == NULL) {
*head = createNode(data);
}
else {
Node* lastNode = *head;
while (lastNode->next != NULL) {
lastNode = lastNode->next;
}
lastNode->next = createNode(data);
}
}
// 打印链表
void printList(LinkedList head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
LinkedList deleteDuplicate(Node* head)
{
if (head == NULL || head->next == NULL)
{
return head;
}
Node* newHead = NULL;
newHead = (Node*)malloc(sizeof(Node)); //创建一个节点,可能第一个就相同
newHead->next = head;
Node* cur = head;
Node* pre = newHead;
while (cur != NULL)
{
bool duplicated = false;
while (cur->next != NULL && cur->data == cur->next->data)
{
duplicated = true;
Node *temp = cur;
cur = cur->next;
free(temp);
}
if (duplicated)
{
pre->next = cur->next;
Node *temp = cur;
cur = cur->next;
free(temp);
}
else
{
pre = cur;
cur = cur->next;
}
}
Node *ret = newHead->next;
free(newHead);
return ret;
}
int main() {
LinkedList head1 = NULL;
append(&head1, 1);
append(&head1, 1);
append(&head1, 3);
append(&head1, 4);
append(&head1, 4);
append(&head1, 5);
append(&head1, 6);
printf("Original List1: ");
printList(head1);
LinkedList head = deleteDuplicate(head1);
printf("deleteDuplicate List: ");
printList(head);
system("pause");
return 0;
}