拆分单循环链表

设单循环链表L1,对其遍历的结果是x1,x2,……xn。将该循环链表拆分成两个单循环链表L1和L2,使得L1中含有原L1表中序号为奇数的节点,L2中含有原L1表中序号为偶数的节点;

#include <iostream>
#include<list>
using namespace std;

template <class T>
struct Node
{
    T data;
    Node<T>* next;
};

template <class T>//尾插建立循环单链表
Node<T>* creat_back( Node<T> * first,int len)
{
    Node<T>* r=first;
    for( int i=0; i<len; i++)
    {
        int data;
        cin>>data;
        Node<T>* pnew=new Node<T>;
        pnew->data=data;
        pnew->next=r->next;
        r->next=pnew;
        r=pnew;
    }
    r->next=first;
    return first;
}

template <class T>//输出链表循环单链表
void show(Node<T>* first)
{
    Node<T>* p=first->next;
    while(p!=first)
    {
        cout<<p->data<<' ';
        p=p->next;
    }
    cout<<endl<<endl;
}

template <class T>
void DePatch(Node<T>* L1,Node<T>* L2 )//将单循环链表L1拆成L1和L2两个单循环链表
{
    L2->next=L2;

    Node<T>* cur=L1->next;
    L1->next=NULL;

    Node<T>* r=L1;
    Node<T>* r2=L2;
    int i=1;

    Node<T>* u=NULL;

    while(cur!=L1)
    {
        if(i%2==1)
        {
            u=cur->next;
            cur->next=L1;
            r->next=cur;
            r=cur;
            cur=u;
            i++;
        }
        else
        {
            u=cur->next;
            cur->next=L2;
            r2->next=cur;
            r2=cur;
            cur=u;
            i++;
        }
    }

}

int main()
{
    Node<int>* first=new Node<int>;
    first->next=NULL;
    Node<int>* L2=new Node<int>;
    L2->next=NULL;
    first= creat_back(first,5);
    DePatch(first,L2);
    show(first);
    show(L2);
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

haibianyoushark

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值