码迷,mamicode.com
首页 > 其他好文 > 详细

链表练习

时间:2016-11-27 23:32:04      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:pre   dup   lin   node   share   int   namespace   nod   let   

#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;
}

shared_ptr<ListNode> InitLinkList()
{
shared_ptr<ListNode> head(new ListNode());
head->val = 1;
shared_ptr<ListNode> tail = head;

InsertNode(tail, 2);
InsertNode(tail, 2);
InsertNode(tail, 2);
InsertNode(tail, 3);
InsertNode(tail, 4);
InsertNode(tail, 4);
InsertNode(tail, 5);

return head;
}

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> deleteDuplicates(shared_ptr<ListNode>& head)
{
if (!head)
return NULL;
shared_ptr<ListNode> dummy(new ListNode());
dummy->val = 0;
dummy->next = head;

shared_ptr<ListNode> node = dummy;
while(node->next != NULL && node->next->next!= NULL){
if(node->next->val == node->next->next->val)
{
int val_prev = node->next->next->val;
while (node->next != NULL && val_prev == node->next->val)
{
node->next = node->next->next;
}
}else{
node = node->next;
}

}
return dummy->next;
}


int main()
{
shared_ptr<ListNode> h = deleteDuplicates(InitLinkList());

CoutLinkList(h);

return 0;
}

 

 

 

#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;
}

shared_ptr<ListNode> InitLinkList()
{
shared_ptr<ListNode> head(new ListNode());
head->val = 1;
shared_ptr<ListNode> tail = head;

InsertNode(tail, 2);
InsertNode(tail, 3);
InsertNode(tail, 4);
InsertNode(tail, 5);

return head;
}

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> ReverLinkList(shared_ptr<ListNode>& head)
{
shared_ptr<ListNode> prev = NULL;
while(head != NULL)
{
shared_ptr<ListNode> curr = head;
head = head->next;
curr->next = prev;
prev = curr;
}

return prev;
}

int main()
{
CoutLinkList(ReverLinkList(InitLinkList()));

return 0;
}

 

链表练习

标签:pre   dup   lin   node   share   int   namespace   nod   let   

原文地址:http://www.cnblogs.com/itdef/p/6107395.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!