發布時間: 2018年11月26日 10:09 時間限制: 1000ms 內存限制: 128M
習題集源碼中出現了 temp->next->prior = p; 本人推斷這里缺少預先的對temp->next==NULL這種情況的判定,所以需加入一個判斷語句解決。
此為非循環的雙向鏈表,末尾空指針沒有前驅,與循環雙向鏈表有所不同。
有n個記錄存儲在帶頭結點的雙向鏈表中,利用雙向冒泡排序法對其按上升序進行排序,請寫出這種排序的算法。(注:雙向冒泡排序即相鄰兩趟排序向相反方向冒泡)。
多組數據,每組數據兩行。第一行為序列的長度n,第二行為序列的n個元素(元素之間用空格分隔,元素都為正整數)。當n等於0時,輸入結束。
每組數據輸出一行,為從小到大排序后的序列。每兩個元素之間用空格隔開。
5 4 5 3 2 9 6 1 3 5 7 9 2 0
2 3 4 5 9 1 2 3 5 7 9
1 //雙向冒泡,最大沉底,最小冒出 2 #include<iostream> 3 using namespace std; 4 typedef struct node 5 { 6 int data; 7 struct node *prior, *next; 8 }node, *LinkList; 9 void TwoWayBubbleSort(LinkList &L) 10 //對存儲在帶頭結點的雙向鏈表L中的元素進行雙向起泡排序。 11 { 12 int exchange = 1;//設標記 13 LinkList head = L;//雙向鏈表頭,算法過程中是向下起泡的開始結點 14 LinkList tail = NULL;//雙向鏈表尾,算法過程中是向上起泡的開始結點 15 while(exchange) 16 { 17 LinkList p = head->next;//p是工作指針,指向當前結點 18 exchange = 0;//假定本趟無交換 19 while (p->next != tail)//向下(右)起泡,一趟有一最大元素沉底 20 { 21 if (p->data > p->next->data)//交換兩結點指針,涉及6條鏈 22 { 23 LinkList temp = p->next; exchange = 1;//有交換 24 p->next = temp->next; 25 if(temp->next)temp->next->prior = p;//先將結點從鏈表上摘下 26 //attention!存在temp->next=NULL的可能,NULL->prior無法訪問 27 temp->next = p; p->prior->next = temp;//將temp插到p結點前 28 temp->prior = p->prior; p->prior = temp; 29 //p = p->next; 30 } 31 else p = p->next;//無交換,指針后移 32 } 33 tail = p;//准備向上起泡 34 p = tail->prior; 35 while (exchange&&p->prior != head)//向上(左)起泡,一趟有一最小元素冒出 36 { 37 38 if (p->data < p->prior->data)//交換兩結點指針,涉及6條鏈 39 { 40 LinkList temp = p->prior; exchange = 1;//有交換 41 p->prior = temp->prior; temp->prior->next = p; 42 //先將temp結點從鏈表上摘下 43 temp->prior = p; p->next->prior = temp; 44 //將temp插到p結點后(右) 45 temp->next = p->next; p->next = temp; 46 } 47 else p = p->prior;//無交換,指針前移 48 } 49 head = p;//准備向下起泡 50 } 51 } 52 void Create(LinkList &L, int n) 53 { 54 LinkList p, rear; 55 L = new node; 56 L->next = NULL; 57 L->prior = NULL; 58 rear = L; 59 while (n--) 60 { 61 p = new node; 62 cin>>p->data; 63 p->next = rear->next; 64 rear->next = p; 65 p->prior = rear; 66 rear = p; 67 } 68 } 69 int main() 70 { 71 int n; 72 while (true) 73 { 74 cin >> n; 75 if (!n)break; 76 else 77 { 78 LinkList L; 79 Create(L, n); 80 TwoWayBubbleSort(L); 81 LinkList p = L->next; 82 while (p->next) 83 { 84 cout << p->data << " "; 85 p = p->next; 86 } 87 cout << p->data << endl; 88 } 89 90 } 91 return 0; 92 }