全部代码及其运行结果
#include <stdio.h>
#include <stdlib.h>
#define max 5
typedef struct listNode
{
char data;
int next;
}*NodePtr;
typedef struct list
{
NodePtr nodes;
int *used;
}*ListPtr;
ListPtr start()
{
ListPtr Header=(ListPtr)malloc(sizeof(ListPtr));
Header->nodes=(NodePtr)malloc(sizeof(NodePtr)*max);
Header->used=(int*)malloc(sizeof(int)*max);
Header->nodes[0].data='\0';
Header->nodes[0].next=-1;
Header->used[0]=1;
for(int i=0;i<max;i++)
{
Header->used[i]=0;
}
return Header;
}
void printList(ListPtr Header)
{
int p=0;
while(p!=-1)
{
printf("%c",Header->nodes[p].data);
p=Header->nodes[p].next;
}
printf("\r\n");
}
void insertList(ListPtr Header,char paraChar,int position)
{
int p,q,r;
int i;
p=0;
for(i=0;i<position;i++)
{
p=Header->nodes[p].next;
if(p==-1)
{
printf("位置%dy已超过链表长度\r\n",position);
return;
}
}
for(i=1;i<max;i++)
{
if(Header->used[i]==0)
{
printf("这个位置允许插入元素\r\n");
Header->used[i]=1;
q=i;
break;
}
}
if(i==max)
{
printf("链表已没有空间了哦\r\n");
return;
}
Header->nodes[q].data=paraChar;
printf("Linking\r\n");
Header->nodes[q].next=Header->nodes[p].next;
Header->nodes[p].next=q;
}
void deleteList(ListPtr Header,char paraChar)
{
int p,q;
p=0;
while(Header->nodes[p].next!=-1 && Header->nodes[Header->nodes[p].next].data!=paraChar)
{
p=Header->nodes[p].next;
}
if(Header->nodes[p].next==-1)
{
printf("链表中不存在该元素\r\n");
return;
}
q = Header->nodes[p].next;
Header->nodes[p].next=Header->nodes[Header->nodes[p].next].next;
Header->used[q]=0;
}
void insertdeleteTest()
{
ListPtr tempList = start();
printList(tempList);
insertList(tempList, 'F', 0);
insertList(tempList, 'I', 1);
insertList(tempList, 'G', 2);
insertList(tempList, 'H', 3);
insertList(tempList, 'T', 4);
printList(tempList);
printf("Deleting 'H'.\r\n");
deleteList(tempList, 'H');
printf("Deleting 'C'.\r\n");
deleteList(tempList, 'C');
printf("Deleting 'K'.\r\n");
deleteList(tempList, 'K');
printList(tempList);
insertList(tempList, 'S', 1);
printList(tempList);
}
int main()
{
insertdeleteTest();
}