使用C语言删除双向链表中的重复结点
时间: 2023-10-11 17:11:52 浏览: 175
可以按照以下步骤来删除双向链表中的重复结点:
1. 定义一个指向当前结点的指针和一个指向下一个结点的指针。
2. 遍历双向链表,对于每个结点,检查是否存在与之相同的结点。
3. 如果存在相同的结点,则删除该结点。删除结点时,需要修改前一个结点的 next 指针和后一个结点的 prev 指针。
4. 继续遍历链表,直到遍历完所有结点。
以下是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
Node* createNode(int val) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = val;
node->prev = NULL;
node->next = NULL;
return node;
}
void deleteDuplicates(Node* head) {
Node* curr = head;
while (curr != NULL) {
Node* temp = curr->next;
while (temp != NULL) {
if (curr->data == temp->data) {
Node* prev = temp->prev;
Node* next = temp->next;
prev->next = next;
if (next != NULL) {
next->prev = prev;
}
free(temp);
temp = next;
} else {
temp = temp->next;
}
}
curr = curr->next;
}
}
void printList(Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
Node* head = createNode(1);
head->next = createNode(2);
head->next->prev = head;
head->next->next = createNode(3);
head->next->next->prev = head->next;
head->next->next->next = createNode(2);
head->next->next->next->prev = head->next->next;
head->next->next->next->next = createNode(4);
head->next->next->next->next->prev = head->next->next->next;
printf("Original List: ");
printList(head);
deleteDuplicates(head);
printf("List after removing duplicates: ");
printList(head);
return 0;
}
```
输出结果为:
```
Original List: 1 2 3 2 4
List after removing duplicates: 1 2 3 4
```
阅读全文