链表删除重复数字求解
【问题描述】试编写算法删除以 L 为头指针(带头结点)的单链表中重复出现的元素。【输入形式】元素个数
按照任意顺序输入多个正整数,每个数之间用一个空格隔开
【输出形式】删除重复元素后的数据,数据之间用空格隔开
【样例输入】 7
6 6 7 8 9 10 11
【样例输出】 6 7 8 9 10 11
大佬们帮帮我
#include <stdio.h> #include <stdlib.h> #define N 1000 typedef struct _node { int data; struct _node *next; } node_t; int main(int argc, const char * argv[]) { int i,num = 0; int input; int array[N] = {0}; //hash表 node_t *L; node_t *head; //头指针(无数据) L = (node_t*)calloc(sizeof(node_t), 1); head = L; //获取输入个数 scanf("%d", &num); //获取全部输入 for (i = 0; i < num; ++i) { scanf("%d",&input); if (array[input] != 0) {//数据已存在,则不加入链表 continue; } array[input] = 1;//hash表置位 head->next = (node_t*)malloc(sizeof(node_t)); head = head->next; head->data = input; head->next = NULL; } //输出 head = L->next; while (head) { printf("%d ", head->data); head = head->next; } //释放内存 while (L) { head = L; L = L->next; free(head); } return 0; }
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> typedef struct _node { int data; struct _node *next; } node_t; node_t * removePreRepeatElement(node_t*, int [], int); int main(int argc, const char * argv[]){ int i, num = 0; int input; node_t *L; printf("初始化链表,请输入元素个数:\n"); scanf("%d", &num); printf("请依次输入各个元素:\n"); node_t *loop = (node_t*)malloc(sizeof(node_t)); L = loop; for (i = 0; i < num; ++i) { scanf("%d", &input); node_t * innerLoop = loop; if (0 != i){ innerLoop = (node_t*)malloc(sizeof(node_t)); loop->next = innerLoop; loop = loop->next; } loop->data = input; loop->next = NULL; } int arr[1000] = { 0 }; L = removePreRepeatElement(L, arr, num); //输出 loop = L; while (loop) { printf("%d ", loop->data); loop = loop->next; } //释放内存 while (L) { loop = L; L = L->next; free(loop); } return 0; } node_t * removePreRepeatElement(node_t* node, int *v, int total) { node_t * loop = NULL; if (NULL != node->next) { loop = removePreRepeatElement(node->next, v, total); } int isExist = 0; int j = 0; for (int i = 0; i < total; i++) { if (0 == *(v + i)) j = i; if (node->data == *(v + i)) { isExist = 1; } } if (!isExist) { *(v + j) = node->data; node->next = loop; return node; } else { free(node); return loop; } }