1. 程式人生 > >單鏈表的順序插入、刪除、查詢/code/c&c++

單鏈表的順序插入、刪除、查詢/code/c&c++

#include<stdio.h>
#include<stdlib.h>


#define MAXLEN 20


typedef struct node
{
int data;
node * next;
}node;


void Createnode(node * & l)//順序插入節點
{
static int len = 0;
if(len >= MAXLEN)
{
printf("Linklist is full!\n");
exit(0);
}
node *s = (node *)malloc(sizeof(node));
if(s == NULL) 
{
printf("No enough memory to allocate!\n");
exit(0);
}
++len;
s->next = NULL;
while(!scanf("%d",&s->data))
{
printf("Input error!\nPlease input an integer:");
fflush(stdin);
}
node *t = l,*pre = t;

if(l == NULL) 
{
l = s;
}
else
{
while(s->data >= t->data && t->next != NULL)
{
pre = t;
t = t->next;
}
if(s->data < t->data)
{
if(pre == t) 
{
s->next = t;
l = s;
}
else
{
s->next = t;
pre->next = s;
}
}
else t->next = s;
}
}


int Seeknode(node * t,int i,int *mydata)//查詢節點
{
int n = 1;
for(; n < i && t != NULL; n++, t = t->next);
if(n == i && t != NULL ) 
{
*mydata = t->data; 
return 1;
}
else return 0;
}


int Deletenode(node * t,int i,int *mydata)//刪除節點
{
int n = 1;
node * pre = t;
for(; n < i && t != NULL; n++, pre = t, t = t->next);
if(t != NULL && n == i) 
{
pre->next = t->next;
*mydata = t->data;
free (t);
return 1;
}
else return 0;
}


void Printlink(node * l)//輸出單鏈表
{
printf("->");
while(l != NULL)
{
printf("%d ",l->data);
l = l->next;
}
putchar('\n');
}


void Deletelink(node * l)//刪除連結串列
{
for(; l != NULL; ) 
{
node *t = l;
l = l->next;
free(t);
}
}


void main()
{
node* head = NULL;
printf("Enter an integer:");
int flag = 1;
char c;
while(flag)
{
Createnode(head);
fflush(stdin);
ERROR:printf("Do you want to continue?(y/n)\n");
c = getchar();
fflush(stdin);
if(c == 'y'|| c == 'Y')
{
printf("Enter an interger:");
}
else if(c == 'n'|| c == 'N') 
{
flag = 0;
}
else 
{
printf("Input error!\n");
goto ERROR;
}
}
flag = 1;
int n;
while(flag)
{
printf("=============================\n1.insert a node\n2.look up a node\n3.delete a node\n4.show the linkline\n0.exit\nPlease input your choice:");
char choice;
fflush(stdin);
scanf("%c",&choice);
putchar('\n');
switch(choice)
{
case '1':
printf("Enter an integer:");
Createnode(head);
break;
case '2':
printf("Which one do you want to look up:");
while(!scanf("%d",&n))
{
printf("Input error!\nPlease input a number:");
fflush(stdin);
}
int mydata;
if(Seeknode(head,n,&mydata)) printf("->%d\n",mydata);
else printf("Not found!\n");
break;
case '3':
printf("Which one do you want to delete:");
while(!scanf("%d",&n))
{
printf("Input error!\nPlease input a number:");
fflush(stdin);
}
int dedata;
if(Deletenode(head,n,&dedata)) printf("Done!\n");
else printf("Not found!\n");
break;
case '4':
Printlink(head);
break;
case '0':
flag = 0;
break;
default:
printf("Input error!\n");
}
}
Deletelink(head);
}