1. 程式人生 > >我的單鏈表的基本操作_C語言

我的單鏈表的基本操作_C語言

以下是帶有頭節點的單鏈表基本操作

/*標頭檔案及函式宣告*/
#include<stdio.h>
#include<malloc.h>

#define OK 1
#define ERROR -1
typedef int Elem;
typedef int Status;

/*節點結構*/
typedef struct Node
{
	Elem data;
	struct Node *next;
}Node, *Nodep;

/*函式宣告*/
Status LK_Init(Nodep *p,int n); 
Status LK_Insert(Nodep p, int
n, Elem e); Status LK_Print(Nodep p); Status LK_Delete(Nodep p, int n); Elem LK_Find(Nodep p, Elem e); Status LK_Amend(Nodep p, int n, Elem e); Status LK_Reverse(Nodep p);
/*初始化單鏈表*/
Status LK_Init(Nodep *p,int n) /*這裡用二級指標是為了把一級指標Nope帶出去*/
{
	*p = (Nodep)malloc(sizeof(Node));  //建立一個頭節點,頭指標*p指向它
	(*p)
->data = 0; //頭節點的data用來存放節點數 Nodep tmp = *p; //宣告一個指標指向頭節點,用於遍歷連結串列 for(; n > 0; --n) /*生成連結串列*/ { Nodep a = (Nodep)malloc(sizeof(Node)); a->data = n; //全部初始化為0 tmp->next = a; tmp = tmp->next; (*p)->data ++; //節點數加1 } tmp->next = NULL; return OK; }
/*單鏈表插入元素   有頭節點的*/
Status LK_Insert(Nodep p, int n, Elem e) { int i = 0; Nodep tmp = p; while(tmp && i < n-1) //此處i的值和tmp指向的節點數一樣 { tmp = tmp->next; i++; } if(!tmp) { printf("LK_Insert error.tmp = NULL\n"); return ERROR; } if(i>n) { printf("LK_Insert error. i>n\n"); return ERROR; } Nodep new = (Nodep)malloc(sizeof(Node)); new->data = e; new->next = tmp->next; tmp->next = new; p->data++; //節點數+1 return OK; }
/*列印單鏈表的所有資料*/
Status LK_Print(Nodep p)
{
	Nodep tmp = p;
	printf("此連結串列總共有 %d 個節點,各節點資料如下:\n", tmp->data);
	tmp = tmp->next;
	while(tmp)
	{
		printf("%d\t",tmp->data);
		tmp = tmp->next;
	}
	putchar('\n');
}
  /*單鏈表查詢一個元素*/
Elem LK_Find(Nodep p, Elem e)
{	
	int pos[50];
	int count, i, k;
	Nodep tmp = p->next;
	count = 0;
	i = 1;
	k = 0;
	while(tmp)
	{
		if(tmp->data == e)
		{
			pos[count++] = i;
		}
		++i;
		tmp = tmp->next;
	}
	if(count)
	{
		printf("找到啦,總共找到 %d 個,分別在第 ", count);
		for(k=0; k<count; ++k)
			printf("%d ", pos[k]);
		printf("個節點\n");
		return OK;
	}
	else
	{
		printf("表中沒有這個元素。\n");
		return ERROR;
	}
}

/*單鏈表刪除一個元素*/
Status LK_Delete(Nodep p, int n)
{
	int i = 0;
	Nodep wtodel, tmp = p;
	while(tmp && i<n-1)   //定位到待刪除元素的前一個元素
	{
		tmp = tmp->next;
		i++;
	}
	if(!tmp || i>n)
	{
		printf("Delete failed.\n");
		return ERROR;
	}
	wtodel = tmp->next;
	tmp->next = tmp->next->next;
	free(wtodel);
	p->data--;
	return OK;
}

/*修改連結串列的一個元素*/
Status LK_Amend(Nodep p, int n, Elem e)
{
	int i = 0;
	Nodep tmp = p;
	while(tmp && i<n)  //定位到第n個
	{
		tmp = tmp->next;
		++i;
	}
	if(!tmp || i>n)
	{
		printf("amend failed.\n");
		return ERROR;
	}
	tmp->data = e;
	return OK;
}
/*反轉連結串列*/
Status LK_Reverse(Nodep p)
{
	Nodep one, temp;
	one = p->next;
	if(one)
		temp = one->next;
	else
	{
		printf("This linklist is null.\n");
		return ERROR;
	}
	while(temp)
	{
		one->next = temp->next;
		temp->next = p->next;
		p->next = temp;
		temp = one->next;
	}
	return OK;
}