删除链表中重复元素

it2026-03-18  3

#include<stdio.h> #include<assert.h> typedef struct node { int val; int no; struct node* next; }node; void list_create(struct node* head, int arr[][2], int n) { for (int i = n - 1; i >= 0; i--) { struct node* new_node = (struct node*)malloc(sizeof(struct node)); new_node->no = arr[i][0]; new_node->val = arr[i][1]; new_node->next = head->next; head->next = new_node; } } void list_show(struct node* head) { struct node* p = head->next; while (p != NULL) { printf("no: %d, val: %d\n", p->no, p->val); p = p->next; } } void parse_list(struct node* head) { assert(head != NULL); struct node* p = head->next; while (p != NULL) { struct node* pre = p; struct node* cur = p->next; while (cur != NULL) { if (cur->no == p->no) { if (cur->val > p->val) { p->val = cur->val; pre->next = cur->next; free(cur); cur = pre->next; } else { p->next = cur->next; free(cur); cur = pre->next; } } else { pre = cur; cur = cur->next; } } p = p->next; } } int main() { struct node* head = (struct node*)malloc(sizeof(struct node)); int arr[5][2] = { {0,1},{0,2},{1,10},{2,20},{2,30} }; head->next = NULL; list_create(head, arr, 5); list_show(head); printf("===========================\n"); parse_list(head); list_show(head); free(head); }
最新回复(0)