题目:
给定一个排序的链表,将其中重复的数全部删除。
比如:1-->1-->1-->2-->3,则返回2-->3
#include <stdio.h> #include <stdlib.h> typedef struct ListNode { ListNode* next; int val; }; ListNode* rmDumplicateNums(ListNode* head) { ListNode stHead = {0}; ListNode* node = head; ListNode* p = &stHead; ListNode* next; ListNode* tmp; bool flag; /*此题采用尾插法即可*/ while (node) { flag = false; next = node->next; /*找到相等的结点*/ while (next && (node->val==next->val)) { next = next->next; flag = true; } /*有就删除*/ if (flag) { while (node != next) { tmp = node->next; free(node); node = tmp; } } /*否则插入*/ else { p->next = node; p = p->next; } node = next; } p->next = NULL; return stHead.next; } void createList(ListNode* head, int* num, int n) { ListNode* p; int i; for (i=0; i<n; i++) { p = (ListNode*)malloc(sizeof(ListNode)); p->next = head->next; p->val = num[i]; head->next = p; } } void printList(ListNode* head) { ListNode* p = head->next; while (p) { printf("%d ", p->val); p = p->next; } printf("\n"); } int main() { ListNode stHead = {0}; int a[] = {5, 5, 1, 1, 1}; createList(&stHead, a, 5); printList(&stHead); stHead.next = rmDumplicateNums(stHead.next); printList(&stHead); return 0; }
时间: 2024-11-13 04:42:41