#include <stdio.h>
#include <stdlib.h>
#define ERROR 0
#define SUCCESSFULLY 1
typedef int ElemType;
typedef int Status;
typedef struct Node
{
ElemType data;
struct Node *next;
} Node, *List;
Status InitList(List *plist)
{
*plist = (Node*)malloc(sizeof(Node));
if(!*plist)
return ERROR;
// 填充头结点的数据域
(*plist) -> data = 0;
(*plist) -> next = NULL;
return SUCCESSFULLY;
}
Status InsertElem(List *plist, int loc, ElemType e)
{
if(loc > (*plist) -> data + 1)
return ERROR;
int i;
Node *pscan = *plist;
for(i = 1; i < loc; i++) // 迭代寻找第loc-1个节点
pscan = pscan -> next;
Node *pnew = (Node*)malloc(sizeof(Node)); // 为新节点分配空间
if(!pnew)
return ERROR;
pnew -> data = e; // 填充数据域
// 连接操作
pnew -> next = pscan -> next;
pscan -> next = pnew;
(*plist) -> data++; // 链表长度计数+1
return SUCCESSFULLY;
}
Status Remove(List *plist, int loc, ElemType *e)
{
if(loc > (*plist) -> data)
return ERROR;
int i;
Node *pscan = *plist;
for(i = 1; i < loc; i++)
pscan = pscan -> next;
pscan -> next = pscan -> next -> next;
(*plist) -> data--; // 计数-1
return SUCCESSFULLY;
}
void ShowList(List *plist)
{
int n = (*plist) -> data, i;
Node *pscan = (*plist) -> next;
for(i = 0; pscan && i < n; i++, pscan = pscan -> next)
printf("%d ", pscan -> data);
printf("\n");
}
void DestroyList(List *plist)
{
Node *pscan = (*plist) -> next,
*ptemp;
while(pscan)
{
ptemp = pscan;
pscan = pscan -> next;
free(ptemp);
}
free(*plist);
}
int main()
{
int input, i = 1;
List mList;
ElemType data;
InitList(&mList);
while(scanf("%d", &input) && input)
InsertElem(&mList, i++, input);
ShowList(&mList);
Remove(&mList, 5, &data);
ShowList(&mList);
DestroyList(&mList);
}
|