2014-12-05 49 views
0

我有一個問題,我試圖創建一個列表,刪除最高值持有號碼,或所有數字具有相同的值,如果該值是最高的列表中。感謝您提供任何提示。雖然循環與指針不起作用

// n,n1,head,next - are pointers 
int j = 0; //this number helps to put pointer forward by one place 
while(n!=0){//should go through every digit of the list 
    if(head == 0){ 
     cout << "list is empty" << endl; 
    } 
    else{ 
     n = head; 
     n1=0; // n1 and n are pointers 
     while(n!=0){ 
      if(n->sk == maxx){//searches for maximum digit in the list 
       break; 
      } 
      else{ 
       n1=n; 
       n=n->next; 
      } 
     } 
     if(head == n){ 
      head = head->next; 
     } 
     else{ 
      n1->next = n->next; 
     } 
     delete n; // deletes the pointer holding the highest value 
    } 
    n = head; //problem is here or somewhere below 
    j++; 
    for(int i=0; i<j;i++){ // this loop should make the pointer point to the first 
     n = n->next;  // number, then the second and so on until the end of list 
    }      // and all the numbers inside the list with the value that 
}      // equals "maxx" should be deleted 

回答

0

好吧,這個問題(它的大部分)是代碼:

while(n!=0){ 
     if(n->sk == maxx){ 
      break; 
     } 
     else{ 
      n1=n; 
      n=n->next; 
     } 
    } 

如果您發現maxx值應刪除節點,繼續尋找,不要break。這樣你就不需要太多的代碼來完成這個任務。

while (n != 0){ 
    if (n->sk == maxx){ 
     node *prev = n->prev; // The previous node. 
     node *tmp = n;  // this assume you have a class node. 
           // temporaly holds the pointer to n. 
     prev->next = n->next; // Connect the previous node with the following one. 
     n = n->next;   // advance n to the next node in the list. 
     delete tmp;   // delete the node. 
    } 
} 
+0

請問你的答案仍然是相同的,如果該列表是雙面? – 2014-12-05 22:55:21

+0

雙面你是指圓形? – 2014-12-05 22:56:56

+0

我的意思是雙鏈表,如果我的英語是正確的,你可以用指針向前和向後移動 – 2014-12-05 22:59:06

2

您應該取消引用指針。現在,你指向他們的地址。看看是否有助於解決您的問題。

0

如果我理解正確的話,你想要什麼,你可以遍歷列表,並保存爲刪除指針:

it = head; 
pos = nullptr; 
while (it != nullptr) { 
    if(it -> sk == maxx) { 
     pos = it; // save ptr 
     it = it -> next; 
     delete pos; // delete saved ptr 
     pos = nullptr; 
    } 
}