单链表的形式:头部有个head节点每个节点都向后关联一个节点
下面是我的单链表的插删改查和反转的操作:
#include<stdio.h> #include<stdlib.h> #include<malloc.h> typedef struct Node* List; #define NODE_SIZE sizeof(struct Node) typedef struct Node S_Node; #define Number int struct Node { Number data; List next; }; List distribute() { List list = (List)malloc(NODE_SIZE); if(list == NULL) { printf("资源分配失败!"); exit(-1); } return list; } List init() //初始化链表 第一个节点为Head节点 { List list = distribute(); list->data = 0; list->next=NULL; } List Reverse(List list) {
// ①->②->③ =》 ②->①->③ =》 ③->②->① List P=NULL,tmp=NULL; list = list->next; P= list; while(list!=NULL&&list->next!=NULL) { tmp=list->next; list->next=tmp->next; tmp->next = P; P= tmp; } list = P; List node= distribute(); node->data=0; node->next=list; return node; } int Find(List list,Number num) { list = list->next; int i = 1; while(list!=NULL&&list->next!=NULL) { if(list->data == num) { return i; } i++; } return -1; } void insert(List list,int position,Number num) { List Next; if(position <1) { printf("输入有误!"); exit(-1); } for(int i =1; i<position&&list->next!=NULL; i++,list=list->next); Next = list->next; List node = distribute(); node->data=num; node->next = Next; list->next=node; } void Remove(List list,int position) { List Next; if(position <1) { printf("输入有误!"); exit(-1); } for(int i =1; i<position&&list->next!=NULL; i++,list=list->next); Next= list->next->next; list->next=Next; } void Edit(List list,int position,Number num) { if(position <1) { printf("输入有误!"); exit(-1); } for(int i =1; i<position&&list->next!=NULL; i++,list=list->next); list->next->data=num; } void print(List list) //打印链表元素 { list = list->next; //Head节点不打印 while(list->next!=NULL||list!=NULL) { printf("%d ",list->data); list=list->next; } } void main() { List list,list2; list =init(); list2=init(); insert(list,1,3); insert(list,2,6); insert(list,3,9); insert(list,2,13); print(list); printf("\n"); Remove(list,3); print(list); printf("\n"); Edit(list,2,222); print(list); printf("\n"); for(int i=1; i<100; insert(list2,i,i),i++); print(list2); list2= Reverse(list2); print(list2); int i = Find(list2,99); printf("%d",i); free(list); free(list2); }