#include<stdio.h> #include<malloc.h> typedef struct node { int data; struct node *next; }node; node *createlink() //创建链表,从文件中读取数据 { node *head =(node*)malloc(sizeof(node)); int t; node *p; node *q; p=q=head; FILE * r= fopen("demo.txt","r"); if(r==NULL) { printf("打开文件失败!"); return NULL; } while(fscanf(r,"%d",&t)!=EOF) { q= (node*)malloc(sizeof(node)); q->data=t; p->next=q; p=q; } p->next=NULL; return head; } //输出链表到屏幕和文件output.txt void outlink(node *head) { node *p=head->next; FILE *w =fopen("output.txt","w"); if(w==NULL) { printf("打开文件失败!"); return; } while(p) { //输出链表节点数据到屏幕 printf("%d ",p->data); //输出链表节点数据到文件output.txt fprintf(w,"%d ",p->data); p=p->next; } printf("\n"); fprintf(w,"\n"); fclose(w); return; } node *BubbleSort(node* head)//冒泡排序 { node *p = head->next; node *pnext; int temp; while( p->next!= NULL) //把小元素都放到前面 { pnext = p->next; while(pnext->next != NULL) { if(p->data>pnext->data) { temp = pnext->data; pnext->data = p->data; p->data = temp; } pnext = pnext->next; } if(p->data>pnext->data) { temp = pnext->data; pnext->data = p->data; p->data = temp; } p = p->next; } return head; } void locate(node *head,int a) 查找元素位置 { node *p = head->next; while(p->data != a) { p = p->next; } printf("The position is %p",p); } void insert(node* head,int a) //插入元素 { node *p = (node *)malloc(sizeof(node)); p->next = head->next; head->next = p; p->data = a; } void Delete(node *head,int a) // 删除元素 { node *p = head; node *q = head->next; while(q->data!=a) { p = p->next; q = q->next; } p->next = q->next; free(q); } /* 单链表反转/逆序 */ node *ListReverse(node* L) { node *current,*pnext,*prev; if(L == NULL || L->next == NULL) return L; current = L->next; /* p1指向链表头节点的下一个节点 */ pnext = current->next; current->next = NULL; while(pnext) { prev = pnext->next; pnext->next = current; current = pnext; pnext = prev; } //printf("current = %d,next = %d \n",current->data,current->next->data); L->next = current; /* 将链表头节点指向p1 */ return L; }
时间: 2024-10-08 20:07:48