zoukankan      html  css  js  c++  java
  • 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;
    }
    

      

  • 相关阅读:
    Django框架-模板层
    Django框架-路由层
    Django流程-以登录功能为例
    常见的MySQL慢查询优化
    函数之二
    python 之 函数
    python 文件操作
    set dict tuple 内置方法
    leetcode
    python 之 数据类型初接触
  • 原文地址:https://www.cnblogs.com/itdef/p/6103187.html
Copyright © 2011-2022 走看看