C/C++整理 --- 單向列表

1:概念:

單向鏈表是鏈表的一種,其特點是鏈表的鏈接方向是單向的,對鏈表的訪問要通過順序讀取從頭部開始。鏈表是使用指 針進行構造的列表,並且是由一個個結點組裝起來的,因此又稱爲結點列表。其中每個結點都有指針成員變量指向列表中的下一個結點,head指針指向第一個結點稱爲表頭,而終止於最後一個指向nuLL的指針。

2:圖示

3:代碼示例

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

/*帶有頭節點的單向鏈表*/
typedef struct Node
{
	int id;		//數據域
	Node *next;	//指針域
}Node;

/*創建頭節點*/
Node * CreateList()
{
	//頭節點作爲標誌,不存儲有效數據
	Node * head = NULL;
	head = (Node *)malloc(sizeof(Node));
	if (head == NULL)
	{
		return NULL;
	}
	head->id = -1;
	head->next = NULL;

	Node * pCur = head;
	Node * pNew = NULL;

	int data;
	while (1)
	{
		printf("please input data:\n");
		scanf("%d", &data);
		if (data == -1)
		{
			break;
		}
		//新節點動態分配內存空間
		pNew = (Node *)malloc(sizeof(Node));
		if (pNew==NULL)
		{
			break;
		}
		//新節點成員變量賦值
		pNew->id = data;
		//pNew->next = NULL;

		//鏈表建立關係
		pCur->next = pNew;	//當前節點的next指向pNew
		pNew->next = NULL;	//pNew的下一個節點指向NULL
		pCur = pNew;	//把pCur的位置移動到pNew
	}
	return head;
}

//在值爲x的結點前,插入值爲y的結點;若值爲x的結點不存在,則插在表尾。
int insertList(Node *head,int x,int y)
{
	if (head == NULL)
	{
		return -2;
	}
	Node *pPre = head;
	Node *pCur = head->next;
	while (pCur != NULL)
	{
		if (pCur->id == x)
		{
			break;
		}
		pPre = pCur;		//pPre指向pCur位置
		pCur = pCur->next;  //pCur指向下一個結點
	}

	/*2種情況
	*1. 找匹配的結點,pCur爲匹配結點,pPre爲pCur上一個結點
	*2. 沒有找到匹配結點,pCur爲空結點,pPre爲最後一個結點
	*/
	Node *pNew = (Node *)malloc(sizeof(Node));
	if (pNew == NULL)
	{
		return -3;
	}
	pNew->id = y;
	pNew->next = NULL;

	pPre->next = pNew;	//pPre下一個指向pNew
	pNew->next = pCur;	//pNew下一個指向pCur
	return 0;
}

/*刪除給定值的節點*/
int deleteList(Node *head, int x)
{
	if (head == NULL)
	{
		return -1;
	}
	Node *pPre = head;
	Node *pCur = head->next;

	while (pCur != NULL)
	{
		if (pCur->id == x)
		{
			pPre->next = pCur->next;
			free(pCur);
			pCur = NULL;
			break;
		}
		pPre = pCur;
		pCur = pCur->next;
	}
	return 0;
}

/*清空鏈表*/
int destroyList(Node *head)
{
	if (head ==NULL)
	{
		return -1;
	}
	Node *tmp = NULL;
	int i = 0;
	while (head != NULL)
	{
		tmp = head->next;
		free(head);
		head = NULL;
		head = tmp;
		i++;
	}
	printf("i=%d\n", i);
	return 0;
}

/*鏈表遍歷*/
int PrintList(Node *head)
{
	if (head == NULL)
	{
		return -1;
	}

	Node *pCur = head->next;
	printf("head->");
	while (pCur != NULL)
	{
		printf("%d -> ", pCur->id);
		pCur = pCur->next;
	}
	printf("NULL\n");
	return 0;
}


int main()
{
	Node *head = NULL;
	head = CreateList();
	PrintList(head);
	insertList(head, 5, 12);
	PrintList(head);
	deleteList(head, 6);
	PrintList(head);
	destroyList(head);
	system("pause");
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章