简体   繁体   English

分割单链表

[英]Splitting Singly Linked List

I'm trying to split a singly linked list into 2 singly linked list. 我正在尝试将单链接列表拆分为2个单链接列表。 l1 will get 30% members of l and l2 will get the next 30% of l. l1将获得l的30%成员,l2将获得l的下一个30%。

#include <iostream>

using namespace std;

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

struct List{
    Node* pHead, *pTail;
};
void CreateList(List &l){
    l.pHead=l.pTail=NULL;
}

int Count(List l){
    int i=0;
    Node*p=l.pHead;
    while (p){
        i++;
        p=p->pNext;
    }
    return i;
}
void RemoveList(List &l){
    Node *p;
    while (l.pHead){
        p=l.pHead;
        l.pHead=p->pNext;
        delete p;
    }
}
void Patition(List &l, List &l1, List &l2){
    int t=Count(l)*0.3;
    cout<<"t="<<t<<endl;
    CreateList(l1);
    CreateList(l2);
    Node *p=l.pHead;
    l1.pHead=p;
    for (int i=0;i<t;i++)
        p=p->pNext;
    l1.pTail=p;
    l.pHead=p->pNext;
    p=l.pHead;
    l2.pHead=p;
    for (int i=0;i<t;i++)
        p=p->pNext;
    l2.pTail=p;
    l.pHead=p->pNext;
    RemoveList(l);
}

I used this code to test your functions: 我使用以下代码来测试您的功能:

int _tmain(int argc, _TCHAR* argv[])
    {
    List l;
    CreateList(l);
    l.pHead = new Node;
    l.pHead->pNext = l.pTail;
    Node *iterator = l.pHead;

// Initial linked list
for (int i = 0; i < 10; i++) {
    Node *newNode = new Node;
    newNode->pNext = iterator->pNext;
    iterator->data = i;
    iterator->pNext = newNode;
    iterator = newNode;
    }

List l1, l2;
Patition(l, l1, l2);


cout << Count(l);
cout << Count(l1);
cout << Count(l2);
return 0;
}

What I found was that in your Count function, your end condition is when p is NULL, but in your partition function, you don't keep your linked list updated with the end pointed to NULL. 我发现,在您的Count函数中,结束条件是p为NULL时,但是在分区函数中,您没有使链表的末尾指向NULL进行更新。

How I would correct this is to simply modify your partition function to 我将如何纠正这一问题,只需将分区功能修改为

void Patition(List &l, List &l1, List &l2){
int t = Count(l)*0.3;
cout << "t=" << t << endl;
CreateList(l1);
CreateList(l2);
Node *p = l.pHead;
l1.pHead = p;
for (int i = 0; i<t; i++)
    p = p->pNext;

// Change
l.pHead = p->pNext;
p->pNext = l1.pTail;
// 
p = l.pHead;
l2.pHead = p;
for (int i = 0; i<t; i++)
    p = p->pNext;

// Change
l.pHead = p->pNext;
p->pNext = l2.pTail;
//

RemoveList(l);
}

This will keep the tail of each linked list pointed to pTail without skipping any nodes from the original linked list. 这将使每个链接列表的尾部始终指向pTail,而不会从原始链接列表中跳过任何节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM