2014-12-05 50 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; 
    } 
}