• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

C语言单链表排序

OC/C/C++ 水墨上仙 2216次浏览

C语言单链表排序

// 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;
}


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);
	return 0;
}


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明C语言单链表排序
喜欢 (0)
加载中……