1.单链表的基本操作
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct LNode{
ElemType data;
struct LNode *next;
}LNode,*LinkList;
LinkList List_HeadInsert(LinkList &L)
{
LNode *s;
int x;
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
scanf("%d",&x);
while(x!=9999)
{
s = (LNode *)malloc(sizeof(LNode));
s->data = x;
s->next = L->next;
L->next = s;
scanf("%d",&x);
}
return L;
}
LinkList List_TailInsert(LinkList &L)
{
L = (LinkList)malloc(sizeof(LNode));
LNode *s,*r=L;
int x;
scanf("%d",&x);
while(x!=9999)
{
s = (LNode *)malloc(sizeof(LNode));
s->data = x;
r->next = s;
r = s;
scanf("%d",&x);
}
r->next = NULL;
return L;
}
LNode *GetElem(LinkList L, int i)
{
int j = 1;
LNode *p = L->next;
if(i==0)
return L;
if(i<1)
return NULL;
while(p&&j<i)
{
p=p->next;
j++;
}
return p;
}
LNode *LocationElem(LinkList L,ElemType e)
{
LNode *p = L->next;
while(p&&p->data!=e)
{
p = p->next;
}
return p;
}
int getLength(LinkList L)
{
int length = 0;
LNode *p =L->next;
while(p)
{
p = p->next;
length++;
}
return length;
}
void printLinkList(LinkList L)
{
LNode *p = L->next;
while(p)
{
printf("%d ",p->data);
p = p->next;
}
putchar('\n');
}
2.在带头结点的单链表L中,删除所有值为x的结点,并释放空间,假设值为x的结点不唯一,试编写算法以实现上述操作。
void Del_X(LinkList &L,ElemType x)
{
LNode *p,*pre,*r;
pre = L;
p = L->next;
while(p!=NULL)
{
if(p->data == x)
{
r = p->next;
pre->next = p->next;
free(p);
p = r;