#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#define OK 0
#define ERROR -1
#define TRUE 1
#define FALSE 0
#define ElemType int
typedef struct Node
{
ElemType data;
struct Node *next;
}Node;
//创建一个空链表,返回链表头结点
Node* createLinkList();
//向头结点为head的链表的pos位置插入元素e,pos从1开始
int insertList(Node *head, int pos, ElemType e);
//删除链表中pos位置的元素,并返回其值
int removeList(Node *head, int pos, ElemType *e);
//得到pos位置的元素
int getElem(Node head, int pos, ElemType *e);
//查找元素e,找到返回TRUE,否则返回FALSE
int findElem(Node head, ElemType e);
//遍历头结点为head的链表
int traverse(Node head);
int main()
{
Node *head = createLinkList();
for (int i=1; i<=1000; i++)
insertList(head, i, i);
ElemType e;
//removeList(head, 500, &e);
getElem(*head, 1000, &e);
printf("findElem:%d\n", e);
traverse(*head);
int result = findElem(*head, 500);
printf("result:%d\n", result);
system("pause");
return 0;
}
Node* createLinkList()
{
//为头结点分配存储空间
Node *head = (Node *)malloc(sizeof(Node));
if (!head)
{
printf("内存分配失败,程序将退出\n");
exit(-1);
}
//创建空链表,所以头结点的下一个结点为NULL
head->next = NULL;
return head;
}
int insertList(Node *head, int pos, ElemType e)
{
if (!head)
{
printf("插入失败,链表不存在\n");
return ERROR;
}
//首先定义一个临时结点指向链表头结点,和一个计数器i
Node *p = head;
int i = 1;
//找到要插入位置的前一个结点
while (p && i < pos)
{
p = p->next;
i++;
}
if (!p || i > pos)
{
printf("插入失败,插入位置有误\n");
return ERROR;
}
//为新插入的结点分配存储空间
Node *newNode = (Node *)malloc(sizeof(Node));
if (!newNode)
{
printf("插入失败,分配存储空间失败,程序将退出\n");
exit(-1);
}
//把新插入结点的下一个结点改为之前结点的下一个结点
newNode->next = p->next;
//把上一个结点的下一个结点改为新插入的结点
p->next = newNode;
newNode->data = e;
return OK;
}
int removeList(Node *head, int pos, ElemType *e)
{
if (!head)
{
printf("删除失败,链表不存在\n");
return ERROR;
}
Node *p = head;
int i = 1;
//找到待删结点的前一个结点
while (p && i < pos)
{
p = p->next;
i++;
}
if (!p || i > pos)
{
printf("删除失败,删除位置有误\n");
return ERROR;
}
//先暂存待删除结点
Node *q = p->next;
//使待删除结点的前一个结点的指针域指向待删除结点的下一个结点
p->next = p->next->next;
//取出删除的值然后释放待删除结点的存储空间
*e = q->data;
free(q);
return OK;
}
int getElem(Node head, int pos, ElemType *e)
{
if (!&head)
{
printf("查找失败,链表不存在\n");
return ERROR;
}
//从第一结点,也就是头结点的下一个结点开始查找
Node *p = head.next;
int i = 1;
while (p && i < pos)
{
p = p->next;
i++;
}
if (!p || i > pos)
{
printf("查找失败,查找位置有误\n");
return ERROR;
}
*e = p->data;
return OK;
}
int findElem(Node head, ElemType e)
{
if (!&head)
{
printf("查找失败,链表不存在\n");
return ERROR;
}
Node *p = head.next;
while (p)
{
if (p->data == e)
{
return TRUE;
}
p = p->next;
}
return FALSE;
}
int traverse(Node head)
{
if (!&head)
{
printf("要遍历的链表不存在\n");
return ERROR;
}
Node *p = head.next;
while (p)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
return OK;
}
线性表的链式存储
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.