#include <stdio.h>
#include <stdlib.h>
// 定义学生结构体
struct Student {
int studentID;
struct Student* next;
};
// 删除相同学号的节点函数
struct Student* deleteDuplicates(struct Student* head) {
if (head == NULL || head->next == NULL) {
return head;
}
struct Student* current = head;
while (current->next != NULL) {
if (current->studentID == current->next->studentID) {
struct Student* duplicate = current->next;
current->next = duplicate->next;
free(duplicate);
} else {
current = current->next;
}
}
return head;
}
// 打印链表函数
void printList(struct Student* head) {
struct Student* current = head;
while (current != NULL) {
printf("Student ID: %d\n", current->studentID);
current = current->next;
}
}
int main() {
// 创建链表
struct Student* head = (struct Student*)malloc(sizeof(struct Student));
head->studentID = 1;
struct Student* second = (struct Student*)malloc(sizeof(struct Student));
second->studentID = 2;
struct Student* third = (struct Student*)malloc(sizeof(struct Student));
third->studentID = 3;
struct Student* fourth = (struct Student*)malloc(sizeof(struct Student));
fourth->studentID = 2;
head->next = second;
second->next = third;
third->next = fourth;
fourth->next = NULL;
printf("Original Linked List:\n");
printList(head);
// 删除相同学号的节点
head = deleteDuplicates(head);
printf("Linked List after removing duplicates:\n");
printList(head);
// 释放内存
struct Student* current = head;
while (current != NULL) {
struct Student* temp = current;
current = current->next;
free(temp);
}
return 0;
}