初始化,创建,遍历
#include "stdio.h"
#include "stdlib.h"
typedef struct node
{
int data;
struct node *p_next;
}Node,*pNode; ;
pNode InitList();
pNode CreateList(pNode list);
void ShowList(pNode list);
int main(){
pNode LIST;
LIST = InitList();
LIST = CreateList(LIST);
printf("\n");
ShowList(LIST);
return 0;
}
pNode InitList(){
pNode list=(pNode)malloc(sizeof(Node));
if(list == NULL){
printf("Failed in init\n");
exit(-1);
}
list->p_next = NULL;
return list;
}
pNode CreateList(pNode list){
int i,length,data;
pNode p_new;
printf("Please input the node counts: ");
scanf("%d",&length);
printf("The list will contain %d nodes!\n",length);
printf("Now,start create list=======\n");
for (i=0;i<length;i++){
printf("Please input Node.No%d data: ",i+1);
scanf("%d",&data);
p_new=(pNode)malloc(sizeof(Node));
p_new->data = data;
p_new->p_next = list->p_next;
list->p_next = p_new;
}
return list;
}
运行结果:
Please input the node counts: 3
The list will contain 3 nodes!
Now,start create list=======
Please input Node.No1 data: 1
Please input Node.No2 data: 2
Please input Node.No3 data: 3
3
2
1
插入
#include "stdio.h"
#include "stdlib.h"
typedef struct node
{
int data;
struct node *p_next;
}Node,*pNode; ;
pNode InitList();
pNode CreateList(pNode list);
pNode InsertList(pNode list);
void ShowList(pNode list);
int main(){
pNode LIST;
LIST = InitList();
LIST = CreateList(LIST);
InsertList(LIST);
printf("\n");
ShowList(LIST);
return 0;
}
pNode InitList(){
pNode list=(pNode)malloc(sizeof(Node));
if(list == NULL){
printf("Failed in init\n");
exit(-1);
}
list->p_next = NULL;
return list;
}
pNode CreateList(pNode list){
int i,length,data;
pNode p_new;
printf("Please input the node counts: ");
scanf("%d",&length);
printf("The list will contain %d nodes!\n",length);
printf("Now,start create list=======\n");
for (i=0;i<length;i++){
printf("Please input Node.No%d data: ",i+1);
scanf("%d",&data);
p_new=(pNode)malloc(sizeof(Node));
p_new->data = data;
p_new->p_next = list->p_next;
list->p_next = p_new;
}
return list;
}
pNode InsertList(pNode list){
int i=0;
int num,data;
pNode p_insert;
printf("Where do you want to insert? n=\n");
scanf("%d",&num);
printf("What data do you want to insert? data=\n");
scanf("%d",&data);
while(list &&i<num){
list=list->p_next;
++i;
}
if(!list||i>num){
printf("Parameter illegal\n");
exit(-1);
}
p_insert=(pNode)malloc(sizeof(Node));
p_insert->data = data;
p_insert->p_next = list->p_next;
list->p_next = p_insert;
}
void ShowList(pNode list)
{
pNode L = list->p_next;
while(L!=NULL)
{
printf("%d\n",L->data);
L=L->p_next;
}
printf("\n");
}
运行结果:
Please input the node counts: 3
The list will contain 3 nodes!
Now,start create list=======
Please input Node.No1 data: 1
Please input Node.No2 data: 2
Please input Node.No3 data: 3
Where do you want to insert? n=
2
What data do you want to insert? data=
5
3
2
5
1