代码如下:
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}Node,*LinkList;
void TailInsertList(LinkList &L)
{
L=(Node*)malloc(sizeof(Node));
L->next=NULL;
Node *r=L;
int x;
scanf("%d",&x);
while(x!=9999)
{
Node *q=(Node*)malloc(sizeof(Node));
q->data=x;
//q->next=NULL;
r->next=q;
r=q;
scanf("%d",&x);
}
r->next=NULL;
}
Node *IndexSearch(LinkList L,int index)//按序号查找
{
Node *t=L->next;
if(index<1) return NULL;
int cnt=1;
while(t!=NULL&&cnt<index)// <=2
{
t=t->next;
cnt++;
}
return t;
}
Node *ValueSearch(LinkList L,int value)//按值查找
{
Node *t=L->next;
while(t!=NULL&&t->data!=value)
{
t=t->next;
}
return t;
}
void Insert1(LinkList &L,int index,int x)
{
Node *t=IndexSearch(L,index-1);//找前驱
Node *q=(Node*)malloc(sizeof(Node));
q->data=x;
q->next=NULL;
q->next=t->next;
t->next=q;
}
void Insert2(LinkList &L,int index,int x)
{
Node *q=(Node*)malloc(sizeof(Node));
q->data=x;
q->next=NULL;
//找第index个结点
Node *t=IndexSearch(L,index);
//后插
q->next=t->next;
t->next=q;
//交换
int m;
m=q->data;
q->data=t->data;
t->data=m;
}
void Insert3(LinkList &L,int index,int x)
{
Node *q=(Node*)malloc(sizeof(Node));
q->data=x;
q->next=NULL;
//找第index个结点
Node *p=IndexSearch(L,index);
Node *prep=IndexSearch(L,index-1);
//后插
q->next=p->next;
p->next=q;
//交换
p->next=q->next;
q->next=p;
prep->next=q;
}
void Delete1(LinkList &L,int index,int &x)//Delete1(L,2,x);
{
Node *p=IndexSearch(L,index-1);
Node *q=p->next;
p->next=q->next;
x=q->data;
}
int Delete2(LinkList &L,int index)
{
Node *p=IndexSearch(L,index-1);
Node *q=p->next;
p->next=q->next;
int x=q->data;
return x;
}
void PrintList(LinkList L)
{
Node *t;
t=L->next;
//t=L;
while(t!=NULL)
{
printf("%d ",t->data);
t=t->next;
}
printf("\n");
}
int LengthList(LinkList L)
{
int cnt=1;
Node *p=L->next;
while(p->next!=NULL)
{
p=p->next;
cnt++;
}
return cnt;
}
void DeleteRange(LinkList &L,int left,int right)
{
Node *preleftnode=IndexSearch(L,left-1);
Node *rightnode=IndexSearch(L,right);
preleftnode->next=rightnode->next;
}
int main()
{
LinkList L;
TailInsertList(L);
PrintList(L);
Node *ans1=IndexSearch(L,11);
if(ans1==NULL) printf("按序号查找中,链表中无此结点!\n");
else printf("ans1->data===%d\n",ans1->data);
Node *ans2=ValueSearch(L,500);
if(ans2==NULL) printf("按值查找中,链表中无此结点!\n");
else printf("ans2->data===%d\n",ans2->data);
Insert1(L,2,666);
PrintList(L);
Insert2(L,3,888);
PrintList(L);
Insert3(L,3,888);
PrintList(L);
int x;
Delete1(L,2,x);
printf("x===%d\n",x);
printf("删除结点的值是:%d\n",Delete2(L,2));
int len=LengthList(L);
printf("len===%d\n",len);
PrintList(L);
DeleteRange(L,2,5);
PrintList(L);
return 0;
}
//150 985 500