|
发表于 2021-11-8 16:35:43
|
显示全部楼层
本帖最后由 jackz007 于 2021-11-8 17:26 编辑
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct node {
- int data ;
- struct node * next ;
- } * PLIST ;
- void show(PLIST head)
- {
- if(head) {
- for(int c = 0 ; head ; head = head -> next) {
- if(c && ! (c % 8)) printf("\n") ;
- else if(c) printf(" , ") ;
- printf("%5d" , head -> data) ;
- c ++ ;
- }
- } else {
- fprintf(stderr , "错误:链表为空!\n") ;
- }
- printf("\n") ;
- }
- PLIST add(PLIST * head)
- {
- PLIST p , p1 , p2 ;
- int d ;
- if(* head) for(p1 = * head , p2 = NULL ; p1 ; p2 = p1 , p1 = p1 -> next) ;
- else p1 = p2 = NULL ;
- printf("输入节点数据 :\n ") ;
- for(;; p2 = p) {
- scanf("%d" , & d) ;
- if(d > 0) {
- if(p = (PLIST) malloc(sizeof(struct node))) {
- p -> data = d ;
- p -> next = NULL ;
- if(p2) p2 -> next = p ;
- else * head = p ;
- } else {
- fprintf(stderr , "内存分配失败!\n") ;
- * head = p ;
- break ;
- }
- } else {
- break ;
- }
- }
- return * head ;
- }
- void deleteIdentica_ListNode(PLIST list)
- {
- PLIST p1 , p2 , p3 ;
- if(list) {
- for(p1 = list ; p1 && p1 -> next ; p1 = p1 -> next) {
- for(p3 = p1 , p2 = p3 -> next ; p2 ; p2 = p3 -> next) {
- if(p2 -> data == p1 -> data) {
- p3 -> next = p2 -> next ;
- free(p2) ;
- } else {
- p3 = p2 ;
- }
- }
- }
- } else {
- fprintf(stderr , "Error : Empty Data Link !\n" ) ;
- }
- }
- void destroy(PLIST head)
- {
- PLIST p1 , p2 ;
- for(p2 = NULL , p1 = head ; p1 ; p1 = p2) {
- p2 = p1 -> next ;
- free(p1) ;
- }
- }
- int main(void)
- {
- PLIST head = NULL ;
- add(& head) ;
- printf("\n") ;
- printf("去除重复前:\n") ;
- show(head) ;
- deleteIdentica_ListNode(head) ;
- printf("去除重复后:\n") ;
- show(head) ;
- destroy(head) ;
- }
复制代码
编译、运行实况:
- D:\0002.Exercise\C>g++ -o x x.c
- D:\0002.Exercise\C>x
- 输入节点数据 :
- 14592 1774 12583 32215 26879 1688 2288 2288 2288 2288 2288 2288 2288 2288 2288
- 2288 8259 857 4989 11010 0
- 去除重复前:
- 14592 , 1774 , 12583 , 32215 , 26879 , 1688 , 2288 , 2288
- 2288 , 2288 , 2288 , 2288 , 2288 , 2288 , 2288 , 2288
- 8259 , 857 , 4989 , 11010
- 去除重复后:
- 14592 , 1774 , 12583 , 32215 , 26879 , 1688 , 2288 , 8259
- 857 , 4989 , 11010
- D:\0002.Exercise\C>
复制代码
这个代码在输入的节点数据值小于 1 时结束输入。
用这个代码测试你的数据,我倒是想知道,什么样的数据能让它崩溃! |
|