單鏈表之逆置

題:編程實現單鏈表的逆置。【美國某著名分析軟件公司2005年面試題】

解析:

單鏈表模型如下圖所示。


進行單鏈表逆置,首先要讓P2的next指向P1,如下圖所示。


然後重新給P1和P2賦值,使他們向後移動,P1指向P2,P2指向P3,如下圖所示。


答案:完整代碼如下:

// P167_example1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <conio.h>

typedef struct student
{
	int data;
	struct student *next;
}node;

//建立單鏈表
node* create()
{
	node *head,*p,*s;
	int x, cycle = 1;
	head = (node *)malloc(sizeof(node));
	p = head;
	while(cycle)
	{
		std::cout<<"please input the data: ";
		std::cin>>x;
		std::cout<<std::endl;
		if(x != 0)
		{
			s = (node *)malloc(sizeof(node));
			s->data = x;
			p->next = s;
			p = s;
		}
		else
			cycle = 0;
	}
	head = head->next;
	p->next = NULL;
	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);
	std::cout<<"Now, These "<<n<<" records are: "<<std::endl;
	p = head;
	if(p != NULL)
	{
		while(p != NULL)
		{
			std::cout<<p->data<<" -> ";
			p = p->next;
		}
		std::cout<<std::endl;
	}
}
//單鏈表刪除結點
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;
			free(p1);
		}
	}
	else
	{
		std::cout<<num<<" could not been found"<<std::endl;
	}
	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(p1 == head)
		{
			p0->next = p1;
			head = p0;
		}
		else
		{
			p0->next = p1;
			p2->next = p0;
		}
	}
	else
	{
		p1->next = p0;
		p0->next = NULL;
	}
	return head;
}
//單鏈表的排序
node *sort(node *head)
{
	node *p;
	int n, 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 _tmain(int argc, _TCHAR* argv[])
{
	node *head;
	head = create();
	print(head);
	//刪除結點
	int num;
	std::cin>>num;
	head = del(head, num);
	print(head);	//打印刪除後的單鏈表
	//插入結點
	std::cin>>num;
	head = insert(head, num);
	print(head);

	//單鏈表排序
	head = sort(head);
	print(head);

	//單鏈表逆置
	head = reverse(head);
	print(head);
	return 0;
}


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