刚上完数据结构课,链表这一块的知识居然忘记了,也上博客看了看别人写的代码,我则是根据他们的代码写了一些代码。话不多说直接上代码。
#include <stdio.h>
#include <stdlib.h>
#define EmleType int
#define true 1
#define false 0
//顺序链表的创建
struct Node
{
EmleType data;
struct Node * next;
};
struct Node * CreateList()
{
EmleType n,i,x;
struct Node * head,* tail,*L;//
head = (struct Node*)malloc(sizeof(struct Node));
head->next = NULL;//先建立一个带头节点的空链表
tail = head;
scanf("%d",&n);
for(i=0;i<n;i++){
L = (struct Node*)malloc(sizeof(struct Node));
scanf("%d",&x);
L->data = x;
L->next = NULL;
tail->next = L;
tail = L;
}
return head;
}
//获取链表中某一个元素的值
EmleType GetElem(struct Node * L,int i,EmleType *e)
{
int j = 1;
struct Node * p = L->next;//p指针指向第一个结点
while(p && j < i){
p = p->next;
j++;
}
if(!p || j > i) /*第i个元素不存在*/
return false;
*e = p->data;
return true;
}
//单链表插入元素,先查找,再插入
EmleType ListInsert(struct Node * L ,EmleType i, EmleType e)
{
EmleType j = 0;
struct Node *p = L,* s;
while(p && j < i-1)
{
p = p->next;
j++;
}
if(!p || j > i-1)
return false;
s = (struct Node *)malloc(sizeof(struct Node));
s->data = e;
s->next = p->next;
p->next = s;
return true;
}
EmleType ListDelate(struct Node * L,EmleType i)
{
EmleType j = 0;
struct Node * p = L ,* q;
while(p && j < i -1)
{
p = p->next;
j++;
}
if(!p->next || j > i-1)
return false;
q = p->next;
p->next = q->next;
free(q);
return true;
}
void ListOutput(struct Node * L)
{
while(L->next!=NULL)
{
printf("%d ",L->next->data);
L=L->next;
}
}
EmleType main()
{
EmleType x,num;
struct Node * L = CreateList();
printf("请输入你需要获取链表的num值\n");
scanf("%d",&num);
if(GetElem(L,num,&x) == true)
{
printf("成功获得第i个元素的值\n");
printf("%d\n",x);
printf("当前链表为:\n");
ListOutput(L);//输出当前链表
printf("\n");
}
else
printf("获取失败");
if(ListInsert(L,num,9) == true)
{
printf("在链表的第%d个位置插入成功\n",num-1);
printf("当前链表为:\n");
ListOutput(L);//输出当前链表
printf("\n");
}
else
printf("插入失败");
if(true == ListDelate(L,num))
{
printf("在链表的第%d个位置删除成功\n",num-1);
printf("当前链表为:\n");
ListOutput(L);//输出当前链表
printf("\n");
}
else
printf("删除失败");
return 0;
}