C++ 删除单链表中值重复的结点_类似选择排序的解法

来源:互联网 发布:淘宝直播链接提取 编辑:程序博客网 时间:2024/06/03 15:01
#include <iostream>


struct Node {
int value;
Node * next;


Node(int data) : value(data), next(nullptr) {};
};


void print(Node *head);
void delRepeatNode(Node *head);


int main()
{
Node n1(1);
Node n2(2);
Node n3(3);
Node n4(1);
Node n5(9);
Node n6(1);
Node n7(2);
Node n8(7);


n1.next = &n2;
n2.next = &n3;
n3.next = &n4;
n4.next = &n5;
n5.next = &n6;
n6.next = &n7;
n7.next = &n8;


delRepeatNode(&n1);
print(&n1);


system("pause");
return 0;
}


void print(Node * head)
{
Node *cur = head;
while (cur != nullptr)
{
std::cout << cur->value << std::endl;
cur = cur->next;
}
}


void delRepeatNode(Node * head)
{
if (head == nullptr)
{
return;
}
int length = 0;
Node *cur = head;
while (cur != nullptr)
{
++length;
cur = cur->next;
}
cur = head;
Node * pre = nullptr, *next = nullptr;


while (cur != nullptr)
{
pre = cur;
next = cur->next;
while (next != nullptr)
{
if (cur->value == next->value)//注意当有值删除和没有值删除的时候情况是不一样的
{
pre->next = next->next;
next = pre->next;
}
else
{
pre = next;
next = next->next;
}

}
cur = cur->next;
}
}
原创粉丝点击