您的位置:首页 > 编程语言 > C语言/C++

C++链表K个节点K个节点的反转((1,2,3,4),如果k是2,反转结果是(2,1,4,3))

2015-05-09 12:50 232 查看
#include <iostream>
using namespace std;

struct Node
{
int val;
struct Node *next;
Node(int x = int()):val(x),next(NULL){}
};

struct List
{
List()
{
head=NULL;
}
void Insert(int x)
{
if(head==NULL)
{
head = new Node(x);
}
else
{
Node *p = head;
Node *s = new Node(x);
while(p->next!=NULL)
{
p=p->next;
}
p->next = s;
}
}
int Size()
{
Node *p = head;
return Size(p);
}
int Size(Node* p)
{
if(p==NULL)return 0;
return Size(p->next)+1;
}
void Inverted(int a,int b)
{
int i = a-1;
int j = b-1;
int size = Size();
if(size<a || b>size)return ;
Node *p = head->next;
Node *q = head;
Node *prve = NULL;//保存反转节点段前面一个节点.
Node *last = NULL;//保存反转节点段后面一个节点.
if(a==1)
{
while(j)
{
last=p->next;
p->next=q;
q=p;
p=last;
j--;
}
head->next = p;
head = q;
}
else
{
p = head;
q = head;
while(i)
{
prve = p;
p=p->next;
i--;
}
while(j)
{
q=q->next;
j--;
}
last=q->next;
Node *save=NULL;
Node *m = p->next;
Node *n = p;
while(p!=last)
{
save = p->next;
p->next = m;
m=p;
p=save;
}
prve->next=m;
n->next = last;
}
}
void Inverted(int k)
{
Node *p = head;
int i = 1;
int count = 0;
while(p!=NULL)
{
p=p->next;
count++;
}
while(count>0)
{
Inverted(i,i+k-1);
if(count>k)
{
count-=k;
i+=k;
if(count<=k)
continue;
}
if(count<=k)
{
i+=count;
count-=k;
}
}
}
void Show()
{
Node *p = head;
while(p!=NULL)
{
cout<<p->val<<"  ";
p=p->next;
}
cout<<endl;
}

private:
Node *head;
};

int main()
{
int Item;
List list;
while(cin>>Item,Item!=-1)
{
list.Insert(Item);
}//1 2 3 4 5 6 7 8
list.Inverted(2);
list.Show();
return 0;
}


复杂链表的复制思路:

struct Node{

Node *next;

Node *other;//随机指向任意一个其他节点,或者指向NULL。

int val;

};

我们现在原来的链表上,如(1,2,3,4,5),每个节点后面复制一个相同的节点,是(1,1,2,2,3,3,4,4,5,5),然后再将心other的指针指向新的相应节点(偶数节点为新的节点),再删除奇数节点,就得到了复杂链表的复制。

给大家提供一个学习C++及查询C++的在线网站,相当与一个APP,www.cplusplus.com。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐