C++11 删除链表重复数值
#include <memory>
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
struct ListNode{
int val;
shared_ptr<ListNode> next;
};
bool InsertNode(shared_ptr<ListNode>& insertPos,int val)
{
shared_ptr<ListNode> node(new ListNode);
if (!node)
return false;
node->val = val;
node->next = NULL;
insertPos->next = node;
insertPos = node;
return true;
}
bool InitLinkList(shared_ptr<ListNode>& head)
{
if ( (!head) || NULL != head->next )
return false;
head->val = 1;
shared_ptr<ListNode> tail = head;
InsertNode(tail, 1);
InsertNode(tail, 2);
InsertNode(tail, 3);
InsertNode(tail, 3);
return true;
}
void CoutLinkList(const shared_ptr<ListNode>& head)
{
for (shared_ptr<ListNode> node = head;
node; node = node->next)
{
cout << node->val << " ";
}
cout << endl;
}
shared_ptr<ListNode> removeDuplicates(shared_ptr<ListNode>& head)
{
if (head == NULL)
{
return NULL;
}
shared_ptr<ListNode> node = head;
while(node->next != NULL){
if(node->val == node->next->val){
shared_ptr<ListNode> tmp = node->next;
node->next = node->next->next;
}else
{
node = node->next;
}
}
return head;
}
int main()
{
shared_ptr<ListNode> head(new ListNode);
InitLinkList(head);
CoutLinkList(head);
head = removeDuplicates(head);
CoutLinkList(head);
return 0;
}
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
浙公网安备 33010602011771号