線性表的鏈式存儲

#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;
}

發佈了33 篇原創文章 · 獲贊 10 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章