本文介绍了正确实现单链列表C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列出雇主名称的列表,例如:

I have a list with names of employers such as:

节点1:吉尔,马特,乔,鲍勃,马特

Node 1: Jill, Matt, Joe, Bob, Matt

节点2:杰夫,詹姆斯,约翰,乔纳森,约翰,爱德华

Node 2: Jeff, James, John, Jonathan, John, Edward

节点3:Matt,Doe, Ron ,Pablo, Ron Chase Ron ,Chase,路易

Node 3: Matt, Doe, Ron, Pablo, Ron, Chase, Ron, Chase, Loui

并且我尝试将其到达重复出现的位置,并将其发送到列表的最前面,并删除该当前节点,以使它看起来像这样

and I'm trying to get it to where if it sees a repeat it will send it to the front of the list and delete that current node, so that it will look like this

节点1:马特,吉尔,乔,鲍勃

Node 1: Matt, Jill, Joe, Bob

节点2: John ,Jeff,James,Jonathan,Edward

Node 2: John, Jeff, James, Jonathan, Edward

节点3: Chase Ron ,Matt,Doe,Pablo,Loui

Node 3: Chase, Ron, Matt, Doe, Pablo, Loui

不幸的是,我的输出接近我想要的.它正在删除重复的条目,但没有发送到最前面.

Unfortunately, My output is close to what I would like. It's deleting the duplicate entries, but it's not sending to the front. .

我的输出:

节点1:吉尔,马特,乔,鲍勃

Node 1: Jill, Matt, Joe, Bob,

推荐答案

好吧,让我们看看:

当您点击if (ptr->data == p->data)时:

  • pp指向列表的末尾
  • p是您的新节点(没有指向它,也没有指向任何东西)
  • ptr指向具有重复数据的节点
  • pp points to the end of the list
  • p is you new node (nothing points to it and it points to nothing)
  • ptr points to the node with duplicate data

要删除节点,您实际上需要使next指针指向ptr,否则如何从列表中删除ptr?因此,您实际上需要检查:

In order to delete the node you need to actually need to have the next pointer pointing to ptr otherwise how can you remove ptr from the list? So you would actually need to check:

if (head && head->data == p->data)
{
    // do nothing as duplicate entry is already head of list
    delete p;
    return;
}

node *ptr = head;
while (ptr)
{
    if (ptr->next && ptr->next->data == p->data)
    {
        node *duplicate = ptr->next;
        ptr->next = duplicate->next; // skip the duplicate node
        duplicate->next = head;      // duplicate points to head
        head = duplicate;            // head is now the duplicate
        delete p;                    // otherwise leaking memory
        return;
    }
    ptr = ptr->next;
}

if (pp) // points to tail as per your code
{
    pp->next = p;
    ++N;
}

这篇关于正确实现单链列表C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 03:45