2016-09-21 6 views
-1

저는 초보자 프로그래머이며 Stack Overflow에 관한 두 번째 질문입니다.연결된 목록 푸시 백 멤버 함수 구현

꼬리 포인터를 사용하여 내 연결된 목록에 대한 푸시 백 기능을 구현하려고합니다. 그것은 충분히 직설적 인 것처럼 보이지만, 나는 무언가를 잊고 있거나 내 논리가 엉망이라는 잔소리가 있습니다. 연결된 목록은 어렵습니다!

template <typename T> 
void LinkedList<T>::push_back(const T n) 
{ 
Node *newNode; // Points to a newly allocated node 

// A new node is created and the value that was passed to the function is stored within. 
newNode = new Node; 
newNode->mData = n; 
newNode->mNext = nullptr; 
newNode->mPrev = nullptr; 

//If the list is empty, set head to point to the new node. 
if (head == nullptr) 
{ 
    head = newNode; 
    if (tail == nullptr) 
    { 
     tail = head; 
    } 
} 
else // Else set tail to point to the new node. 
    tail->mPrev = newNode; 
} 

이 글을 읽을 시간을내어 주셔서 감사합니다 :

여기 내 코드입니다.

+1

먼저 'head'가 null이면 'tail'도 이미 null이어야합니다. 그렇지 않으면 무언가 잘못되었습니다. 둘째,'tail '이리스트의 마지막 노드를 가리키면'newNode-> mPrev'가 * that * ('tail')을 가리 키지 않아야하고,'tail = newNode;'를 설정하면됩니까? – WhozCraig

+1

코드를 작성하기 전에 상자에 데이터를, 상자 사이의 선을 링크로 사용하여 연결된 목록을 종이에 그려야합니다. 그런 다음 종이에서 본 내용을 코드로 번역하십시오. 그렇게하면 WhozCraig가 지적한 것처럼 잘못된 행동을하는 것입니다. – PaulMcKenzie

+0

WhozCraig, 당신은 절대적으로 맞습니다. 내 else 문은 newNode-mPrev = tail이어야합니다. 나는 바보 같은 실수를하는 것을 알고 있었다! Paul, 나는 그것들 중 일부를 논문에 적었다. 나는 그것을 전부 써야했다! 조언 감사합니다. –

답변

2

틀린 노드에 잘못된 mPrev을 가리키고 있습니다. 그리고 이전 tail 노드의 mNext을 설정하지 않습니다.이 노드가 null이 아니면 목록의 전달 체인을 계속 진행하지 마십시오.

template <typename T> 
void LinkedList<T>::push_back(const T n) 
{ 
    Node *newNode; // Points to a newly allocated node 

    // A new node is created and the value that was passed to the function is stored within. 
    newNode = new Node; 
    newNode->mData = n; 
    newNode->mNext = nullptr; 
    newNode->mPrev = tail; // may be null, but that's ok. 

    //If the list is empty, set head to point to the new node. 
    if (head == nullptr) 
     head = newNode; 
    else 
     tail->mNext = newNode; // if head is non-null, tail should be too 
    tail = newNode; 
} 
+0

감사합니다, WhozCraig. 정말로이 과정을 이해하게 도와주었습니다. –