#include<stdio.h>
#include<stdlib.h>
#define m 10
typedef struct List{
int number;
int data;
struct List *next;
}List , *Plist;
int a[2][m]={
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
80,81,82,83,84,85,86,87,88,89
};
int Searchtime=0;
//创建
Plist Create_List(Plist head){
int i=0;
Plist Point=NULL;
Plist New=NULL;
head = (Plist) malloc(sizeof(List));
if(head==NULL){
printf("内存分配失败!\n");
exit(0);
}
head->number = a[0][i];
head->data = a[1][i];
head->next = NULL;
Point = head;
for(i=1;i<m;i++){
New = (Plist) malloc(sizeof(List));
New->number = a[0][i];
New->data = a[1][i];
New->next = NULL;
Point->next = New;
Point = New;
}
printf("链表创建成功!\n");
return head;
}
//插入(空链表,新节点代表首节点,找不到则插入链表尾部)
Plist Insert(Plist head, int key){
Plist Point = head;
Plist New = NULL;
New = (Plist) malloc (sizeof(List));
New->next = NULL;
New->number = 10;
New->data = 85;
while(1){
if(Point == NULL || key == -1){
New->next=Point;
head=New;
break;
}
if(Point->number == key){
New->next = Point->next;
Point->next = New;
break;
}
if(Point->next == NULL){
New->next = Point->next;
Point->next = New;
break;
}
Point = Point->next;
}
return head;
}
//删除
Plist Delete(Plist head, int key){
Plist Point = head;
if(Point == NULL){
exit(0);
}
if(Point->number == key){
head = Point->next;
free(Point);
printf("删除头节点成功!\n");
}
else{
Plist Back = NULL;
while(1){
Back = Point;
Point= Point->next;
if(Point == NULL){
printf("索引号:%d,Not Found!\n",key);
break;
}
if(Point->number == key){
Back->next = Point->next;
printf("[%d]删除成功!\n",Point->number);
free(Point);
break;
}
}
}
return head;
}
//查找
int Search(Plist head, int key){
Plist Point = head;
while(Point != NULL){
Searchtime++;
if(Point->number==key){
printf("[%d]->",key);
printf("[%d,%d]\n",Point->number,Point->data);
return 1;
}
Point = Point->next;
}
return 0;
}
//释放
void Free_List(Plist head){
Plist Point = NULL;
while(head != NULL){
Point = head;
head = Point->next;
free(Point);
}
}
//输出
void Print(Plist head){
Plist Point=NULL;
Point=head;
while(Point !=NULL ){
printf("(%d,%3d) ",Point->number,Point->data);
Point=Point->next;
}
printf("\n");
}
//逆序
Plist Invert(Plist head){
if(head == NULL || head->next == NULL){
printf("逆序失败!\n");
exit(0);
}
printf("逆序后:\n");
Plist Point = NULL;
Plist Back = NULL;
Plist Next = NULL;
Back = head;
Point = Back->next;
Back->next = NULL;
while(Point != NULL){
Next = Point->next;
Point->next = Back;
Back = Point;
Point = Next;
}
head = Back;
return head;
}
int main(){
int i=0;
Plist head = NULL;
head=Create_List (head );
head = Insert(head, i);
Print(head);
head = Delete(head, i);
Print(head);
Search(head, 10);
head=Invert( head );
Print(head);
return 0;
}
链表的增删、查找以及逆序
最新推荐文章于 2022-04-20 16:49:15 发布