链表划分

链表划分:

给定一个链表和一个值key,将链表划分成两部分,使得划分后小于key的结点在前,大于key的结点在后。在上述两部分中要保持链表中的出现顺序。

如:给定:1->4->3->2->5->2 和 key = 3.

返回:1->2->2->4->3->5.

程序实现:

 1 /************************************
 2 File Name:ListPartition.cpp
 3 Author: godfrey
 4 Created Time: 2016/04/29
 5 *************************************/
 6 #include <iostream>
 7 #include <cstdio>
 8 #include <cstdlib>
 9 using namespace std;
10 
11 typedef struct tagSNode{
12     int value;
13     tagSNode* pNext;
14 
15     tagSNode(int v):value(v),pNext(NULL) {}
16 }SNode;
17 //打印链表
18 void Print(SNode* pHead){
19     SNode* p = pHead->pNext;
20     while(p){
21         cout<<p->value<<" ";
22         p = p->pNext;
23     }
24     cout<<endl;
25 }
26 //删除分配结点空间
27 void Destroy(SNode* pHead){
28     SNode* p;
29     while(pHead){
30         p = pHead->pNext;
31         delete pHead;
32         pHead = p;
33     }
34 }
35 //链表划分
36 void ListPartition(SNode* pHead,int key){
37     //使用链表分别存储小于key,大于key的数值
38     SNode* p1Head = new SNode(0);
39     SNode* p2Head = new SNode(0);
40     //两个链表当前最后一个元素
41     SNode* p1Tail = p1Head;
42     SNode* p2Tail = p2Head;
43     SNode* p = pHead->pNext;
44     //遍历原链表
45     while(p){
46         if(p->value < key){
47             p1Tail->pNext = p;
48             p1Tail = p;
49         }
50         else{
51             p2Tail->pNext = p;
52             p2Tail = p;
53         }
54         p = p->pNext;
55     }
56     //将p2链表拼接到p1链表尾部
57     p1Tail->pNext = p2Head->pNext;
58     p2Tail->pNext = NULL;
59     //将拼接好的链表赋值给原链表
60     pHead->pNext = p1Head->pNext;
61 
62     delete p1Head;
63     delete p2Head;
64 }
65 
66 int main()
67 {
68     SNode* pHead = new SNode(0);
69     for(int i=0;i<10;i++){
70         SNode* p = new SNode(rand()%100);
71         p->pNext = pHead->pNext;
72         pHead->pNext = p;
73     }
74 
75     Print(pHead);
76     ListPartition(pHead,50);
77     Print(pHead);
78     Destroy(pHead);
79     return 0;
80 }

运行结果:

转载请注明出处:http://www.cnblogs.com/gaobaoru-articles/

posted on 2016-04-29 14:21  Brainer-Gao  阅读(234)  评论(0编辑  收藏  举报

导航