输入3 4 5 6 7 9999一串整数,9999代表结束,通过尾插法新建链表,查找第二个位置的值并输出,在2个位置插入99,输出为 3 99 4 5 6 7,删除第4个位置的值,打印输出为 3 99 4 6 7。
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct LNode{
ElemType data;
struct LNode * next;
}LNode,*LinkList;
LinkList list_head_insert(LinkList &L)
{
LinkList s;
int x;
L=(LinkList) malloc(sizeof (LNode));
L->next=NULL;
scanf("%d",&x);
while (x!=9999)
{
s=(LinkList) malloc(sizeof(LNode) );
s->data=x;
s->next=L->next;
L->next=s;
scanf("%d",&x);
}
return L;
}
void PrintList(LinkList L)
{
L = L->next;
while (L != NULL)
{
printf("%3d", L->data);//打印当前结点数据
L = L->next;//指向下一个结点
}
printf("\n");
}
LinkList list_tail_insert(LinkList &L)
{
int x;
L=(LinkList) malloc(sizeof (LNode));
LNode* s,*r=L;
scanf("%d",&x);
while (x!=9999)
{
s=(LinkList) malloc(sizeof (LNode));
s->data=x;
r->next=s;
r=s;
scanf("%d",&x);
}
r->next=NULL;
return L;
}
LinkList GetElem(LinkList L,ElemType i)
{
int j=0;
while (L&&j<i)
{
L= L->next;
j++;
}
return L;
}
bool ListFrontInsert(LinkList L,int i,ElemType e)
{
LinkList search;
search= GetElem(L,i-1);
if(search==NULL)
{
return false;
}
LinkList s=(LinkList) malloc(sizeof (LNode));
s->data=e;
s->next=search->next;
search->next=s;
return true;
}
bool list_delete(LinkList L,int i)
{
LNode *s= GetElem(L,i);
LNode *p= GetElem(L,i-1);
if(s==NULL || p==NULL)
{
return false;
}
p->next=s->next;
free(s);
return true;
}
int main()
{
LinkList L,search;
//list_head_insert(L);
// PrintList(L);
list_tail_insert(L);
search=GetElem(L,2);
if(search)
{
printf("%d\n",search->data);
}
ListFrontInsert(L,2,99);
PrintList(L);
list_delete(L,4);
PrintList(L);
}