您的位置:首页 > 其它

单链表基本操作

2016-01-05 13:25 288 查看
#include<windows.h>//源代码已经在VS2012编译通过
#include<stdio.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
typedef int Status;
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode *next;
}LNode, *LinkList;
//采用头插法建立单链表
LinkList CreateListHead(LinkList &L)
{
LNode *s;//指示新生成的结点
int x;
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
scanf("%d",&x);
while(x != 0)
{
s = (LNode*)malloc(sizeof(LNode));
s->data = x;
s->next = L->next;
L->next = s;
scanf("%d",&x);
}
return L;
}
//采用尾插法建立单链表
LinkList CreateListTail(LinkList &L)
{
LNode *s;//指示新生成的结点
LNode *t;//指示单链表的尾结点
int x;
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
scanf("%d",&x);
bool Is = true;
while(x != 0)
{
s = (LNode*)malloc(sizeof(LNode));
s->data = x;
s->next = NULL;
if(Is)
{
L->next = s;
t = s;
Is = false;
}
else
{
t->next = s;
t = t->next;
}
scanf("%d",&x);
}
return L;
}
void PrintLinkList(LinkList L)
{
LNode *s = L->next;
if(s == NULL)
{
printf("The LinkList is empty!");
}
int Is = true;
while(s != NULL)
{
if(Is)
{
printf("%d",s->data);
s = s->next;
Is = false;
}
else
{
printf("--%d",s->data);
s = s->next;
}
}
printf("\n");
}
LNode *GetElemByNum(LinkList L,int n)
{
LNode * s = L->next;
for(int i = 2;i <= n;i++)
{
s = s->next;
}
return s;
}
LNode *GetElemByValue(LinkList L,int e)
{
LNode *s = L->next ;
while(s != NULL)
{
if(s->data == e)
{
return s;
}
else
{
s = s->next;
}
}
return s;
}
LinkList InsertByNum(LinkList &L,int n,int e)
{
LNode *t = GetElemByNum(L,n-1);
LNode *s = (LNode*)malloc(sizeof(LNode));
s->data = e;
s->next = t->next;
t->next = s;
return L;
}
LinkList DeleteByNum(LinkList &L,int n)
{
LNode *t = GetElemByNum(L,n-1);
LNode *s = t->next;
t->next = s->next;
free(s);
return L;
}
LinkList DeleteByValue(LinkList &L,int e)
{
LNode *t = L;
LNode *s = L->next;
while(s != NULL)
{
if(s->data == e)
{
t->next = s->next;
free(s);
return L;
}
else
{
s = s->next;
t = t->next;
}
}
return L;
}
//求单链表的长度
int GetLength(LinkList L)
{
LNode *s = L->next;
int len = 0;
while(s != NULL)
{
len++;
s = s->next;
}
return len;
}
int main()
{
//采用头插法建立单链表并打印输出
LinkList LinkList1;
LinkList1 = CreateListHead(LinkList1);
PrintLinkList(LinkList1);
//采用尾插法建立单链表并打印输出
LinkList LinkList2;
LinkList2 = CreateListTail(LinkList2);
PrintLinkList(LinkList2);
//按序号查找结点
LNode *L1 = GetElemByNum(LinkList1,4);
printf("按序号查找结果:%d--%d\n",L1,L1->data);
//按值查找结点
LNode *L2 = GetElemByValue(LinkList2,4);
printf("按值查找结果:%d\n",L2);
//按序号插入结点并打印输出
LinkList1 = InsertByNum(LinkList1,2,100);
PrintLinkList(LinkList1);
//按序号删除结点并打印输出
LinkList1 = DeleteByNum(LinkList1,2);
PrintLinkList(LinkList1);
//按值删除结点并打印输出
LinkList2 = DeleteByValue(LinkList2,2);
PrintLinkList(LinkList2);
//求单链表的长度
int length1 = GetLength(LinkList1);
printf("The length of LinkList1 is %d\n",length1);
int length2 = GetLength(LinkList2);
printf("The length of LinkList2 is %d\n",length2);
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息