#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct Node {
int data;
struct Node* next;
};
// 插入节点到链表尾部
void append(struct Node** headRef, int newData) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *headRef;
newNode->data = newData;
newNode->next = NULL;
if (*headRef == NULL) {
*headRef = newNode;
return;
}
while (last->next != NULL) {
last = last->next;
}
last->next = newNode;
}
// 反转链表
void reverse(struct Node** headRef) {
struct Node* prev = NULL;
struct Node* current = *headRef;
struct Node* next = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*headRef = prev;
}
// 删除链表中的重复元素
void removeDuplicates(struct Node* head) {
struct Node* current = head;
struct Node* next_next;
if (current == NULL) {
return;
}
while (current->next != NULL) {
if (current->data == current->next->data) {
next_next = current->next->next;
free(current->next);
current->next = next_next;
} else {
current = current->next;
}
}
}
// 打印链表元素
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
append(&head, 1);
append(&head, 2);
append(&head, 2);
append(&head, 3);
append(&head, 4);
append(&head, 4);
append(&head, 5);
printf("Original list: \n");
printList(head);
// 反转链表
reverse(&head);
// 删除重复元素
removeDuplicates(head);
// 再次反转链表
reverse(&head);
printf("List after reverse and removing duplicates: \n");
printList(head);
return 0;
}