创建一个单链表,除头结点之外有7个有效结点,存放数字分别为:32、28、45、67、14、18、29,建表过程要求使用头插入法。要求:在67与14之间插入结点,插入结点存放数字为100,将插入前和插入后的各结点数字输出。
可能使用到的函数:①初始化单链表;②头插入法建表;③单链表插入算法;④单链表输出算法;⑤主函数。
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct node
{
ElemType data;
struct node* next;
}SlinkNode;
//1初始化链表
SlinkNode* InitLink(SlinkNode* h)
{
h = (SlinkNode*) malloc(sizeof(SlinkNode));
h->next = NULL;
return h;
}
//头插法
SlinkNode* InsertHead(SlinkNode* h,ElemType e)
{
SlinkNode *t;
t = (SlinkNode*)malloc(sizeof(SlinkNode));
t->data = e;
t->next = h->next;
h->next = t;
return h;
}
//显示链表
void showList(SlinkNode* h)
{
SlinkNode* p = h->next;
while (p)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
//链表的长度
int Length(SlinkNode* h)
{
SlinkNode* p = h->next;
int len=0;
while(p)
{
len++;
p = p->next;
}
return len;
}
//在pos位置插入元素
SlinkNode* InsertAt(SlinkNode* h,int pos,ElemType e)
{
SlinkNode* p,*t;
if (pos <1 || pos > Length(h))
{
return 0;
}
t = (SlinkNode*)malloc(sizeof(SlinkNode));
t->data = e;
p = h;
while(--pos && p)
{
p = p->next;
}
if(p)
{
t->next = p->next;
p->next = t;
}
return h;
}
//释放内存
void FreeList(SlinkNode* h)
{
SlinkNode* p;
while(h)
{
p = h->next;
free(h);h=0;
h = p;
}
}
int main()
{
SlinkNode* h = 0;
int i;
int a[7]={32,28,45,67,14,18,29};
//初始化单链表h
h = InitLink(h);
//头插法建表
for(i=6;i>=0;i--)
{
h = InsertHead(h,a[i]);
}
printf("插入前链表数据:");
showList(h);
//在67与14之间插入100(14的位置是5)
h = InsertAt(h,5,100);
//显示链表
printf("插入100后链表数据:");
showList(h);
//释放链表
FreeList(h);
return 0;
}