#include<stdio.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
struct LinkNode{
int data;
struct LinkNode *next;
};
void print(LinkNode *L){
LinkNode *p;
p = L->next;
while(p != 0){
printf("%d、",p->data);
p = p->next;
}
printf("
");
}
int Length_LinkList(LinkNode *L){
LinkNode *p;
int len = 0;
p = L->next;
while(p != NULL){
len++ ;
p = p->next;
}
return len;
}
LinkNode* FindI_LinkNode(LinkNode *L,int i){
LinkNode *p;
int j = 1;
p = L->next;
while(j < i){
p = p->next;
j++;
}
return p;
}
int FindE_LinkNode(LinkNode* L,int e){
LinkNode *p;
int count=0;
p=L->next;
while(p != NULL)
{
count++;
if(p->data==e)
return (count);
p=p->next;
}
return 0;
}
int Insert_head(LinkNode* &L,int x){
LinkNode *t;
t = new LinkNode;
t->data = x;
t->next = L->next;
L->next = t;
return OK;
}
int Insert_end(LinkNode *L,int x){
LinkNode *t;
t = new LinkNode;
t->data = x;
while(L->next != NULL){
L = L->next;
}
L->next = t;
t->next = NULL;
return OK;
}
int Insert_LinkNode(LinkNode *L,int i,int x){
if(i < 1 || i > Length_LinkList(L)){
printf("插入位置错误!
");
return ERROR;
}
LinkNode *p;
if(i == 1)
p = L;
else
p = FindI_LinkNode(L,i-1);
Insert_head(p,x);
return OK;
}
int Del_Head(LinkNode *L){
if(L->next != NULL){
LinkNode *p;
p = L->next;
L->next = p->next;
delete p;
}else{
printf("空表!
");
return FALSE;
}
}
int Del_End(LinkNode *L){
if(L->next != NULL){
LinkNode *p;
LinkNode *q;
int i;
p = L->next;
for(i = 1;i < Length_LinkList(L) - 1;i++){
p = p->next;
}
q = p->next;
p->next = NULL;
delete q;
}else{
printf("空表!");
}
}
int Del_i(LinkNode* L,int i){
if(i<1 || i>Length_LinkList(L))
{
printf("删除位置不合法!");
return 0;
}
LinkNode *p;
if(i==1)
p=L;
else
p=FindI_LinkNode(L,i-1);
Del_Head(p);
return OK;
}
int main(){
int i,x,count,m;
LinkNode *H;
LinkNode *add;
H = new LinkNode;
H->next = NULL;
printf("输入数据:
");
while(1){
scanf("%d",&i);
if(i == 9999){
break;
}else{
Insert_end(H,i);
}
}
printf("The LinkNode elem is:");
print(H);
printf("1.请输入从表头插入的数据:");
scanf("%d",&i);
Insert_head(H,i);
printf("The LinkNode elem is:");
print(H);
printf("2.请输入从表尾插入的数据:");
scanf("%d",&i);
Insert_end(H,i);
printf("The LinkNode elem is:");
print(H);
printf("3.请输入要插入的位置、数据(空格隔开):
");
scanf("%d %d",&i,&x);
Insert_LinkNode(H,i,x);
printf("The LinkNode elem is:");
print(H);
printf("4.请输入要查询的位置:");
scanf("%d",&i);
if(i < 1 || i > Length_LinkList(H)){
printf("查询位置不合法!
");
}else{
add = FindI_LinkNode(H,i);
int e = add->data;
printf("位置:%d的数据是:%d
",i,e);
}
printf("4.请输入要查询的元素:
");
scanf("%d",&i);
m = FindE_LinkNode(H,i);
if(m == 0){
printf("查无此元素!
");
}else{
printf("数据:%d所在的位置是:%d
",i,m);
}
Del_Head(H);
printf("5.删除首元节点后:
The LinkNode elem is:");
print(H);
Del_End(H);
printf("6.删除表尾节点后:
The LinkNode elem is:");
print(H);
printf("7.指定删除节点的位置:
");
scanf("%d",&i);
if(i < 1 || i > Length_LinkList(H)){
printf("指定位置不合法!
");
}else{
Del_i(H,i);
printf("6.删除指定节点后:
The LinkNode elem is:");
print(H);
}
count = Length_LinkList(H);
printf("8.此链表长度为:%d
",count);
return 0;
}