链表的插入 删除 排序 倒叙

#include <iostream>
using namespace std;
#include <stdio.h>
#include <stdexcept>
#include <conio.h>
#include <string.h>
#include <stack>


struct Node
{
	int data;
	struct Node *next;
};

Node *Creat()
{
	Node *head,*p,*s;
	head=(Node *)malloc(sizeof(Node));
	p=head;
	int n;
	while(scanf("%d",&n)&&n)
	{
		s=(Node *)malloc(sizeof(Node));
		s->data=n;
		p->next=s;
		p=s;
	}
	head=head->next;
	p->next=NULL;
	return head;
}

int Length(Node *head)
{
	Node *p;
	p=head;
	int len=0;
	while(NULL!=p)
	{
		p=p->next;
		++len;
	}	
	return len;
}

Node *Del(Node *&head,int num)
{
	Node *p1,*p2;
	p1=head;
	while (num!=p1->data&&NULL!=p1->next)
	{
		p2=p1;
		p1=p1->next;
	}
	if (num==p1->data)
	{
		if(p1==head)
		{
			head=p1->next;
			free(p1);
		}
		else
		{
			p2->next=p1->next;
		}
	}
	else
	{
		printf("%d cound not be found\n",num);
	}
	return head;
}
//插入头结点时,这是头结点改变了,所以这里要注意  就是所谓的引用与指针的区别
//函数体内 要修改一个变量的值该怎么做呢???不懂的自己百度
//这种情况老是容易忘记,请仔细注意了
Node *Insert(Node *&head,int num)
{
	Node *p0,*p1,*p2;
	p1=head;
	p0=(Node*)malloc(sizeof(Node));
	p0->data=num;
	while (num>p1->data&&NULL!=p1->next)
	{
		p2=p1;
		p1=p1->next;
	}
	if (num<=p1->data)
	{
		if (head==p1)
		{
			p0->next=head;
			head=p0;
		}
		else
		{
			p2->next=p0;
			p0->next=p1;
		}
	}
	else
	{
		p1->next=p0;
		p1->next->next=NULL;
	}
	return head;
}


Node *Sorted(Node *head)//简单的冒泡排序法
{
	Node *p1,*p2;
	p1=head;
	p2=head;
	int len=Length(head);
	if (NULL==head||NULL==head->next)
		return head;
	for (int i=0; i<len; ++i)
	{
		p2=p1;
		for (int j=i+1; j<len; ++j)
		{
			if(p1->data>p2->next->data)
			{
				p1->data^=p2->next->data;
				p2->next->data^=p1->data;
				p1->data^=p2->next->data;
			}
			p2=p2->next;
		}
		p1=p1->next;
	}
	return head;
}


Node *Reverse(Node *&head)
{
	Node *p1,*p2,*p3;
	p1=head;
	if (NULL==head||NULL==head->next)
	{
		return head; 
	}
	p2=p1->next;
	while (p2)
	{
		p3=p2->next;
		p2->next=p1;
		p1=p2;
		p2=p3;
	}
	head->next=NULL;
	head=p1;
	return head;
}


void Print(Node *head)
{
	Node *p;
	p=head;
	while (NULL!=p)
	{
		printf("%d ",p->data);
		p=p->next;
	}
	printf("\n");
}
 
#include "list.h"

int main()
{
	Node *head;
	int del_num,insert_num;
	head=Creat();
	Print(head);
	cout<<"\n\n";
	cout<<"链表的长度: "<<Length(head)<<"\n\n";
		cin>>del_num;
		Del(head,del_num);
		cout<<"删除后的链表: ";
		Print(head);

		while(cin>>insert_num&&insert_num)
		{
				cout<<"插入后的链表: ";
				Insert(head,insert_num);
				Print(head);
		}
	
		Reverse(head);
		cout<<"倒序输出:";
		Print(head);
				
	
		Sorted(head);
		cout<<"排序后的链表: ";
		Print(head);
	
	system("pause");

	return 0;
}



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值