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;
}
运行结果:
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