题目描述:以给定值x为基准将链表分割成两部分,所有小于x的节点排在大于等于x的节点之前。
思路:设置largehead,largetail和smallhead,smalltail,第一次找到小于或者大于等于x的节点时就更新head指针,后面遍历链表每次更新tail指针。
实现没考虑空链表等边界情况。
1 #include <iostream> 2 #include <string> 3 #include <fstream> 4 #include <map> 5 #include <algorithm> 6 #include <vector> 7 #include <ctime> 8 #include <bitset> 9 10 using namespace std; 11 12 template<typename T> 13 class Node 14 { 15 public: 16 Node<T> *next; 17 T data; 18 19 Node(T d):data(d),next(NULL){} 20 void appendToTail(T d) 21 { 22 Node<T> *end = new Node<T>(d); 23 Node<T> *n = this; 24 while(n->next != NULL) 25 { 26 n = n->next; 27 } 28 n->next = end; 29 } 30 }; 31 32 int main() 33 { 34 Node<int> *head = new Node<int>(1); 35 int i; 36 head->appendToTail(4); 37 for(i = 2 ; i < 6 ; ++i) 38 { 39 head->appendToTail(i); 40 } 41 //2.4 42 head->appendToTail(4); 43 head->appendToTail(3); 44 Node<int> *largeHead = NULL; 45 Node<int> *largeTail = NULL; 46 Node<int> *smallHead = NULL; 47 Node<int> *smallTail = NULL; 48 Node<int> *headOrg = head; 49 int x = 3; 50 while(head != NULL) 51 { 52 if(head->data >= x) 53 { 54 if(largeHead == NULL) 55 { 56 largeHead = head; 57 largeTail = head; 58 } 59 else 60 { 61 largeTail->next = head; 62 largeTail = head; 63 } 64 } 65 else 66 { 67 if(smallHead == NULL) 68 { 69 smallHead = head; 70 smallTail = head; 71 } 72 else 73 { 74 smallTail->next = head; 75 smallTail = head; 76 } 77 } 78 head = head->next; 79 } 80 smallTail->next = largeHead; 81 while(smallHead != NULL) 82 { 83 cout<<smallHead->data<<endl; 84 smallHead = smallHead->next; 85 } 86 return 0; 87 }