1. 程式人生 > >程式設計師面試寶典(第三版)——單鏈表的基本操作:建立,求長度,輸出,排序,插入,刪除,逆置

程式設計師面試寶典(第三版)——單鏈表的基本操作:建立,求長度,輸出,排序,插入,刪除,逆置

程式設計實現一個單鏈表的建立,求單鏈表的長度,列印輸出單鏈表,對單鏈表進行排序,插入元素,刪除元素,對單鏈表進行逆置。

我是借鑑參考資料,然後自己寫規範,對函式都進行了呼叫,每一次呼叫,都有輸出單鏈表。程式完整,已除錯執行。

源程式:

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<conio.h>
using namespace std;
typedef struct student
{
	int data;
	struct student *next;
}node;
//建立單鏈表
node *creat()
{
	node *head,*p,*s;
	int x,cycle=1;
	head=(node*)malloc(sizeof(node));
	p=head;
	cout<<"請輸入單鏈表的資料,以0作為結束標識:"<<endl;
	while(cycle)
	{	
		cin>>x;
		if(x!=0)//以0為標識
		{
			s=(node *)malloc(sizeof(node));
			s->data=x;
			p->next=s;
			p=s;
		}
		else cycle=0;
	}
	head=head->next;
	p->next=NULL;
	cout<<endl;
	return (head);
}
 //求單鏈表的長度
int length(node *head)
{
	int n=0;
	node *p;
	p=head;
	while(p!=NULL)
	{
		p=p->next;
		n++;
	}
	return(n);
}
//輸出單鏈表
void print(node *head)
{
	node *p;int n;
	n=length(head);
	cout<<"現在,長度為"<<n<<"的單鏈表更新為:"<<endl;
	p=head;
	if(head!=NULL)
	{
		while(p!=NULL)
		{
			cout<<p->data<<'\t';
			p=p->next;
		}
	}
	printf("\n");
}
//刪除單鏈表中的某個元素
node *del(node *head,int num)
{
	node *p1,*p2;
	p1=head;
	while(num!=p1->data&&p1->next!=NULL)
	{
		p2=p1;
		p1=p1->next;
	}
	if(num==p1->data)
	{
		if(p1==head)
		{
			head=p1->next;
			free(p1);
		}
		else
			p2->next=p1->next;
	}
	else
		cout<<num<<"沒有在單鏈表中找到!"<<endl;//printf("\n%d 沒有在單鏈表中找到!",num);
	return head;
}
//在單鏈表中插入一個元素
node *insert(node *head,int num)
{
	node *p0,*p1,*p2;
	p1=head;
	p0=(node *)malloc(sizeof(node));
	p0->data=num;
	while(p0->data>p1->data&&p1->next!=NULL)
	{
		p2=p1;p1=p1->next;
	}
	if(p0->data<=p1->data)
	{
		if(head==p1)
		{
			p0->next=p1;
			head=p0;
		}
		else
		{
			p2->next=p0;
			p0->next=p1;
		}
	}
	else
	{
		p1->next=p0;
		p0->next=NULL;
	}
	return head;
}
//對單鏈表從小到大排序:
node *sort(node *head)
{
	node *p;
	int n;int temp;
	n=length(head);
	if(head==NULL||head->next==NULL)
		return head;
	p=head;
	for(int j=1;j<n;++j)
	{
		p=head;
		for(int i=0;i<n-j;++i)
		{
			if(p->data>p->next->data)
			{
				temp=p->data;
				p->data=p->next->data;
				p->next->data=temp;
			}
			p=p->next;
		}
	}
	return head;
}
//對單鏈表進行逆置
node *reverse(node *head)
{
	node *p1,*p2,*p3;
	
	if(head==NULL||head->next==NULL)
		return head;
	p1=head,p2=p1->next;
	while(p2)
	{
		p3=p2->next;
		p2->next=p1;
		p1=p2;
		p2=p3;
	}
	head->next=NULL;
	head=p1;
	return head;
}
int main()
{
	node *head;
	int n,del_num,insert_num;

	head=creat();
	print(head);

	cout<<"\n單鏈表的長度: ";
	n=length(head);
	cout<<n<<endl;
	
	cout<<"\n請對單鏈表排序:";
	head=sort(head);
	print(head);

	cout<<"\n請輸入單鏈表中要刪除的資料: ";
	cin>>del_num;
	head=del(head,del_num);
	print(head);

	cout<<"\n請輸入單鏈表中要插入的資料:";
	cin>>insert_num;
	head=insert(head,insert_num);
	print(head);

	cout<<"\n請對單鏈表進行逆置:";
	head=reverse(head);
	print(head);

	return 0;
}
執行結果:

總結:單鏈表的基本操作,包括建立單鏈表,對單鏈表求長度,列印輸出單鏈表,對單鏈表進行排序,刪除元素,插入元素,對單鏈表逆置。這些操作都是程式設計師必須掌握的,雖然它是一種相對簡單的資料結構,但是能夠做到熟練掌握運用也是需要花時間的。