#include <bits/stdc++.h>
using namespace std;
typedef int State;
typedef int ElemType;
typedef struct Node
{
ElemType data;
struct Node *next;
} Node;
typedef struct Node *LinkList;
State InitLinkList(LinkList *L)
{
*L = new Node;
if (!*L)
{
return 0;
}
else
{
return 1;
}
(*L)->next = NULL;
}
State isEmpty(LinkList L)
{
if (L->next)
{
return 0;
}
else
{
return 1;
}
}
State listLength(LinkList L)
{
int i = 0;
LinkList p;
p = L->next;
while (p)
{
i++;
p = p->next;
}
return i;
}
State insertList(LinkList *L, int i, ElemType e)
{
LinkList p;
p = *L;
int j = 1;
while (p && j < i)
{
p = p->next;
j++;
}
if (!p)
{
return 0;
}
LinkList q;
q = new Node;
q->data = e;
q->next = p->next;
p->next = q;
return 1;
}
State deleteList(LinkList *L, int i, ElemType *e)
{
LinkList p;
p = *L;
int j = 1;
while (p && j < i)
{
p = p->next;
j++;
}
if (!p)
{
return 0;
}
LinkList q;
q = p->next;
p->next = q->next;
*e = q->data;
free(q);
return 1;
}
State clearList(LinkList *L)
{
LinkList p, q;
p = (*L)->next;
while (p) {
q = p->next;
free(p);
p = q;
}
(*L)->next = NULL;
return 1;
}
State getElem(LinkList L, int i, ElemType *e)
{
LinkList p;
p = L->next;
int j = 1;
while (p && j < i)
{
p = p->next;
j++;
}
if (!p)
{
return 0;
}
*e = p->data;
return *e;
}
State localElem(LinkList L, ElemType e)
{
LinkList p;
p = L->next;
int j = 1;
while (p) {
if (p->data == e)
{
return j;
}
p = p->next;
j++;
}
return 0;
}
State headCreatList(LinkList *L)
{
*L = new Node;
(*L)->next = NULL;
for (int i = 1; i < 9; i++)
{
LinkList p = new Node;
p->data = i;
p->next = (*L)->next;
(*L)->next = p;
}
return 1;
}
State tailCreatList(LinkList *L)
{
(*L) = new Node;
LinkList t;
t = (*L);
for (int i = 5; i < 14; i++)
{
LinkList p = new Node;
p->data = i;
t->next = p;
t = p;
}
t->next = NULL;
return 1;
}
State printLinkList(LinkList L)
{
LinkList p;
p = L->next;
int i = 1;
while (p)
{
printf("第%d个结点的元素值为%d\n", i, p->data);
p = p->next;
i++;
}
return 1;
}
int main()
{
LinkList L1, L2;
int e;
printf("使用头插法创建单链表可得结果L1:\n");
headCreatList(&L1);
printLinkList(L1);
printf("使用尾插法创建单链表可得结果L2:\n");
tailCreatList(&L2);
printLinkList(L2);
printf("其中L1的长度为%d, L2的长度为%d\n", listLength(L1), listLength(L2));
printf("向单链表L1的第三个位置插入一个666元素可得:\n");
insertList(&L1, 3, 666);
printLinkList(L1);
printf("将单链表L2的第三个位置的元素删除可得:\n");
deleteList(&L2, 3, &e);
printf("删除的元素为:%d\n", e);
printf("现在的单链表L2为:\n");
printLinkList(L2);
printf("单链表是否存在元素666?存在则返回其位置,不存在则返回0:\n");
printf("单链表L1中666元素的位置为:%d\n", localElem(L1, 666));
printf("单链表L2中666元素的位置为:%d\n", localElem(L2, 666));
getElem(L1, 8, &e);
printf("获得L1中的第8个元素为:%d\n", e);
printf("清空单链表可得L1: \n");
clearList(&L1);
printLinkList(L1);
}
|