#include<stdio.h>
#define OK 1
#define ERROR 0
typedef int Status;
typedef int ElemType;
typedef struct LinkList
{
ElemType data;
struct Node* next;
} Node, LinkList, *LinkListPtr;
LinkListPtr create_head(int n)
{
LinkListPtr list, node;
ElemType data;
int i;
list = (LinkListPtr)malloc(sizeof(Node));
list->next = NULL;
printf("请输入结点数据值\n");
for(i = 0; i < n; i++)
{
node = (LinkListPtr)malloc(sizeof(Node));
scanf("%d", &data);
node->data = data;
node->next = list->next;
list->next = node;
}
return list;
}
LinkListPtr create_tail(int n) {
LinkListPtr list, node, p;
ElemType data;
int i;
list = (LinkListPtr)malloc(sizeof(Node));
list->next = NULL;
p = list;
printf("请输入结点数据值\n");
for(i = 0; i < n; i++) {
node = (LinkListPtr) malloc(sizeof(Node));
scanf("%d", &data);
node->data =data;
while(p->next) {
p = p->next;
}
node->next = NULL;
p->next = node;
}
return list;
}
Status insertLinkList(LinkListPtr linkListPtr, ElemType e, int pos)
{
LinkListPtr p = linkListPtr;
int i = 0;
while(i < pos-1 && p) {
p = p->next;
i++;
}
if(!p || i > pos) {
printf("第%d个元素不存在\n", pos);
return ERROR;
}
LinkListPtr newNode = (LinkListPtr)malloc(sizeof(Node));
newNode->data = e;
newNode->next = p->next;
p->next = newNode;
return OK;
}
Status deleteByOrder(LinkListPtr list, int pos, ElemType* e) {
LinkListPtr p = list;
LinkListPtr q;
int i = 0;
while(p && i < pos-1) {
p = p->next;
i++;
}
if(!p || i > pos) {
printf("\n第%d个结点不存在", pos);
return ERROR;
}
q = p->next;
*e = q->data;
p->next = q->next;
free(q);
return OK;
}
Status clearList(LinkListPtr list) {
LinkListPtr p = list->next;
LinkListPtr q;
while(p) {
printf("%d\t", p->data);
q = p;
p = p->next;
free(q);
}
list->next = NULL;
}
Status printLinkList(LinkListPtr list)
{
LinkListPtr p;
p = list->next;
while(p) {
printf("%d\t", p->data);
p = p->next;
}
printf("\n");
}
Status reserve(LinkListPtr list) {
LinkListPtr p, q, r;
p = list;
q = p->next;
while(q->next) {
r = q->next;
q->next = p;
p = q;
q = r;
}
q->next = p;
p = list->next;
p->next = NULL;
list->next = q;
return OK;
}
void main()
{
ElemType e = 100;
LinkListPtr list2 = create_tail(10);
insertLinkList(list2, e, 4);
insertLinkList(list2, e, 4);
insertLinkList(list2, e, 1);
insertLinkList(list2, e, 18);
printLinkList(list2);
deleteByOrder(list2, 1, &e);
printf("被删除的元素值: %d\n", e);
deleteByOrder(list2, 4, &e);
printf("被删除的元素值: %d\n", e);
deleteByOrder(list2, 4, &e);
printf("被删除的元素值: %d\n", e);
printLinkList(list2);
printf("逆置链表:\n");
reserve(list2);
printLinkList(list2);
printf("清空链表:");
clearList(list2);
printLinkList(list2);
}