链表面试题

1.简单链表

给出如下链表,有以下要求:


要求1:逆序打印该链表(如:3->2->5->1->4结果应为41523)

解题思路:利用栈的后进先出特性来解决

代码如下:

void R_print(Node* Head)//逆序打印链表
	{
		if(Head==NULL)
			return ;
		stack<int> s1;
		Node* cur=Head;
		while(cur)
		{
			s1.push(cur->_data);
			cur=cur->_next;
		}
		//cout<<s1.top()<<endl;
		while(!s1.empty())
		{
			cout<<s1.top()<<"-";
            s1.pop();		
		}
	
	}
也可将链表逆置,在按顺序进行打印


Node* Reverse(Node* Head)//逆置链表
	{
		if(Head==NULL||Head->_next==NULL)
			return Head;
		Node* new_Head=NULL;
		Node* cur=Head;
		while(cur)
		{
			Node* tmp=cur;
           cur=cur->_next;	
		   tmp->_next=new_Head;
		   new_Head=tmp;
		}
	return new_Head;
	}


运行结果:




要求2:对此链表进行排序
1.冒泡排序:

	void BubbleSortList(Node* Head)//链表排序(冒泡)
	{
		if(Head==NULL||Head->_next==NULL)//判断空链表和只有一个节点
			return ;
		
		Node* Tail=NULL;
		Node* Next=NULL;
		Node* cur=NULL;
		while(Tail!=Head)
		{
			cur=Head;
			Next=cur->_next;
			bool exchange=false;
			while(Next!=Tail)			{
				if(cur->_data>Next->_data)
				{
				swap(cur->_data,Next->_data );
				}
			cur=cur->_next;
			Next=Next->_next;
			}
			if(exchange==true)//优化
				break;
			Tail=cur;
		}
	}
快速排序:(前后指针)

	

void QuickSortList(Node* Head,Node* Tail)
	{
		if(Head==NULL||Head==Tail||Head->_next ==Tail)
			return ;
		Node* prev=Head;
		Node* cur=Head->_next;
		int key=Head->_data ;
		while(cur!=Tail)
		{
			if(cur->_data <key)
			{
				prev=prev->_next ;
				if(prev!=cur)
				{
					swap(cur->_data ,prev->_data );
				}	
			}
			cur=cur->_next;
		}

	  swap(prev->_data ,Head->_data );
	  QuickSortList(Head,prev);
	  QuickSortList(prev->_next ,Tail);
	}

运行结果:



2.复杂链表的复制

第一步:插入新节点

第二步:拷贝random

第三步:拆分链表

truct Node
{
	Node(int data)
	:_data(data)
	 ,_next(NULL)
	,_random(NULL)
	{}
public:
	Node* _next;
	Node* _random;
	int _data;
	
};




代码如下:


	Node* ComplexCopy(Node* Head)
	{
		Node* new_Head;
		if(Head==NULL)
		{
			new_Head=new Node(0);
			return new_Head;
		}
		Node* cur=Head;
		while(cur)//增加节点
		{
			Node* Next=cur->_next;
			Node* new_node=new Node(cur->_data);
			new_node->_next =Next;
			cur->_next=new_node;
			cur=cur->_next->_next;
		}
		cur=Head;
		while(cur)
		{
		cout<<cur->_data <<"->";
		cur=cur->_next;
		}
		cout<<endl;
		cur=Head;
		while(cur)//拷贝random
		{
			cur->_next->_random=cur->_random;
			cur=cur->_next->_next;
		}
	
		new_Head=Head->_next;
		Node* new_Tail=new_Head;
		cur=Head;
		while(cur&&cur->_next)//拆分链表
		{
			Node* Next=cur->_next;
			cur->_next=cur->_next ->_next;
			new_Tail->_next=Next;
			new_Tail=Next;
			cur=Next;
			
		}
		return new_Head;
	}	




到此结束!!!!!!!!!!!1




  • 0
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值