1. 程式人生 > >c++學習筆記—單鏈表基本操作的實現

c++學習筆記—單鏈表基本操作的實現

用c++語言實現的單鏈表基本操作,包括單鏈表的建立(包括頭插法和尾插法建表)、結點的查詢、刪除、排序、列印輸出、逆置、連結串列銷燬等基本操作。

IDE:vs2013


具體實現程式碼如下:

#include "stdafx.h"
#include <malloc.h>
#include <iostream>
using namespace std;
typedef struct Lnode
{
	int data;
	struct Lnode *next;
}*node;
node head_creat()   //頭插法建立單鏈表
{
	node head = (struct Lnode *)malloc(sizeof(struct Lnode));
	head->next = NULL;
	node p;
	int temp;
	while (cin >> temp)
	{
		p = (node)malloc(sizeof(struct Lnode));
		p->data = temp;
		p->next = head->next;
		head->next=p;
	}
	return head;
}
bool search(node h, int target)     //查詢某元素是否在連結串列中
{
	int flag = 0;
	node p = h->next;
	if (h->next == NULL)
		return false;
	for (; p != NULL;)
	{
		if (p->data == target)
		{
			flag = 1;
			break;
		}
		else
			p++;
	}
	if (flag)
		return true;
	else
		return false;
}
node back_creat()   //尾插法建立單鏈表
{
	node head = (struct Lnode *)malloc(sizeof(struct Lnode));
	head->next = NULL;
	node p;
	node r = head;
	int temp;
	while (cin >> temp)
	{
		p = (node)malloc(sizeof(struct Lnode));
		p->data = temp;
		r->next=p;
		r = p;
	}
	r->next = NULL;
	return head;
}
void print(node h)    //列印單鏈表
{

	node p = h->next;
	while (p)
	{
		cout << p->data << endl;
		p = p->next;
	}
}
node delete_node(node h,int del_val)     //刪除指定值的節點
{
	node p = h->next;
	node q = h;
	node r=NULL;
	while (p)
	{
		if (p->data == del_val)
		{
			r = p;
			p = p->next;
			q->next = p;
			free(r);
		}
		else
		{
			q = p;
			p = p->next;
		}
	}
	return h;
}
node sort(node h)     //對連結串列進行排序(降序)
{
	node p=h->next;
	if (p->next == NULL)
		return h;
	
	for (; p != NULL; p = p->next)
	{
		for (node q = p->next; q != NULL; q = q->next)
		{
			int temp;
			if (p->data > q->data)
			{
				temp = p->data;
				p->data = q->data;
				q->data = temp;
			}
		}
	}
		return h;
}
node reverse(node h)  //逆置連結串列
{
	node p, q;
	p = h->next;
	h->next = NULL;
	while (p)
	{
		q = p;
		p = p->next;
		q->next = h->next;
		h->next = q;
	}
	return h;
}
void destroy_List(node head)  //銷燬連結串列
{
	if (NULL == head)
	{
		return;
	}
	if (NULL == head->next)
	{
		free(head);
		head = NULL;
		return;
	}
	node p = head->next;
	while (NULL != p)
	{
		node tmp = p;
		p = p->next;
		free(tmp);
	}
	free(head);
	head = NULL;
}
int _tmain(int argc, _TCHAR* argv[])
{
	cout << "---------------構造連結串列-------------" << endl;
	node h = back_creat();
	cout << "---------------列印連結串列-------------" << endl;
	print(h);
	//cout << "-----------刪除指定值後列印連結串列-----" << endl;
	//h = delete_node(h, 2);
	//print(h);
	cout << "-----------排序後列印連結串列------------" << endl;
	h = sort(h);
	print(h);
	cout << "-----------逆置後列印連結串列------------" << endl;
	h = reverse(h);
	print(h);
	destroy_List(h);
	return 0;
}

執行結果: