2014-06-24 1 views
-1

C++에서 연결된 목록을 역순으로 변환하는 방법을 쓰고 있습니다. void 반환 형식 대신 Node*을 사용하려고하지만 여러 오류가 있습니다.C++에서 연결된 목록을 뒤집는 방법

내 방법 코드는 ..

Node* Reverse(Node *head) 
    { 
    struct node* prev = NULL; 
    struct node* current = head; 
    struct node* next; 
    while (current != NULL) 
     { 
     next = current->next; 
     current->next = prev; 
     prev = current; 
     current = next; 
     } 
     head = prev; 
    } 

내가 수신하고 컴파일 시간 오류 메시지 ..

solution.cc: In function 'Node* Reverse(Node*)': 
    solution.cc:24:22: error: cannot convert 'Node*' to 'Reverse(Node*)::node*' in initialization 
    node* current = head; 
       ^
    solution.cc:28:24: error: invalid use of incomplete type 'struct Reverse(Node*)::node' 
    next = current->next; 
        ^
    solution.cc:23:14: error: forward declaration of 'struct Reverse(Node*)::node' 
    struct node* prev = NULL; 
     ^
    solution.cc:29:16: error: invalid use of incomplete type 'struct Reverse(Node*)::node' 
    current->next = prev; 
      ^
    solution.cc:23:14: error: forward declaration of 'struct Reverse(Node*)::node' 
    struct node* prev = NULL; 
     ^
    solution.cc:33:10: error: cannot convert 'Reverse(Node*)::node*' to 'Node*' in assignment 
head = prev; 
    ^
    solution.cc:34:1: error: no return statement in function returning non-void [-Werror=return-type] 
    } 
^
    cc1plus: some warnings being treated as errors 
+0

'node'와'Node'의 정의는 무엇입니까? –

+0

1 문제는 당신이 struct 노드를 완전히 선언하지 않아야한다는 것입니다.이 메서드 앞에 struct 노드와 같은 forward decleration 만 넣으면됩니다. 전체 신고서를 함께 제출하십시오. 또한 함수는 Node o * 타입을 반환하지만 아무 것도 반환하지 않는다고 말합니다. –

+0

당신은 어디에서나'struct'를 입력 할 필요가 없습니다. – Zsolt

답변

2

Nodenode으로 동일하지 않습니다 당신은 return

Node* Reverse(Node *head) 
{ 
struct Node* prev = NULL; 
struct Node* current = head; 
struct Node* next; 
while (current != NULL) 
    { 
    next = current->next; 
    current->next = prev; 
    prev = current; 
    current = next; 
    } 
    head = prev; 
    return head; 
} 
누락
-1

노드가 아니라 노드 여야합니다. 더하기 당신은 Node * 타입을 반환해야합니다.

Node* Reverse(Node *head) 
{ 
    struct Node* prev = NULL; 
    struct Node* current = head; 
    struct Node* next = new Node; //new node; 
    while (current != NULL) 
    { 
    next = current->next; 
    current->next = prev; 
    prev = current; 
    current = next; 
    } 
    head = prev; 

    return head;   //return head as it will return the whole list. 

} 
+0

왜 메모리가 누설되는 걸까요? – Quentin

관련 문제