2010-07-01 2 views
-3

어떻게 하나의 노드 만 남았을 때 void del_begin()이 충돌합니까 (노드를 추가하는 다른 기능이 있습니까)?C++ (2 페이지)의 링크 목록

#include <iostream> 
using namesspace std; 

node *start_ptr = NULL; 
node *current; 
int option = 0; 
void del_end() 
{ 
    node *temp, *temp2; 
    temp = start_ptr; 
    if (start_ptr == NULL) 
     cout << "There are no nodes" << endl; 
    else 
    { 
     while (temp->nxt != NULL) 
     { 
      temp2 = temp; 
      temp = temp->nxt; 
     } 
     delete temp; 
     temp2->nxt = NULL; 
    } 
} 
void display() 
{ 
    node *temp; 
    temp = start_ptr; 
    cout << endl; 
    if (temp == NULL) 
     cout << "There are no nodes to display" << endl; 
    else 
    { 
     while(temp != NULL) 
     { 
     cout << temp->name << ", " << temp->profession << ", " << temp->age; 
     if (temp == current) 
      cout << "***"; 
     cout << endl; 
     temp = temp->nxt; 
     } 
     cout << endl; 
    } 
} 

int main() 
{ 
    start_ptr = NULL; 
    int option; 
     do 
    { 
     display(); 
     cout << "0 for EXIT" << endl; 
     cout << "1 to ADD TO END" << endl; 
     cout << "2 to ADD TO BEGINNING" << endl; 
     cout << "3 to DELETE LAST" << endl; 
     cout << "4 to DELETE BEGINNING" << endl; 
     cout << ">>"; 
     cin >> option; 
     switch (option) 
     { 
     case 1 : add_end(); break; 
     case 2 : add_begin(); break; 
     case 3 : del_end(); break; 
     case 4 : del_begin(); break; 
     } 
    } 
    while (option != 0); 
    return 0; 
} 
+6

당신은 우리에게'del_begin()'에 대한 코드를 보여주지 않았다 .... –

+4

어, C++은 어디 있습니까? Cout에서 제외하면 C < –

+0

list <> 또는 slist <>가 아마도 더 잘 작동 할 것입니다. –

답변

1
당신은 우리에게 del_begin()에 대한 코드를 보여주지 않았다

하지만 del_end() 당신이 언급하고있는 경우 버그 (단일 노드 목록)를 갖는다.

노드가 하나만있는 경우, 귀하의 while 루프가 실행되지 않을 것이다, 당신은 라인에 도착하면 temp2가 초기화되지 않은 것 :

temp2->nxt = NULL; 

충돌을! 노드가 하나만있는 경우

+0

어떻게 수정합니까? – danutenshu

+1

@danutenshu : 대신 라이브러리 목록 클래스를 사용하여 문제를 해결할 수 있습니다. 자기 자신을 굴릴만한 이유가 있습니까? –

+0

내 자신의 링크 목록을 만들도록 지정되었습니다. 더 설명해 주시겠습니까? 나는 – danutenshu

0

, 당신의 while 루프는 실행되지 않을 것이다, 그리고 TEMP2는 삭제에 적절하게 초기화되지 않는

start_ptr & 전류를 초기화되지 않은 것입니다.

이 방법은 모든 종류의 스레드로부터 안전하지 않지만 예를 들어 목록에서 제거하기 전에 다음 항목을 삭제하는 경우입니다.