簡體   English   中英

將節點插入鏈表僅開始或結束

[英]Inserting node to linked list only goes to beginning or end

我對這段代碼感到困惑。 我想將名稱為“ Joshua”的節點插入到具有“ James”的節點之后的鏈接列表中。 但是,我錯了,它僅基於“ insert(” Joshua“,2);”中的整數值將其添加到列表的開頭或結尾。

#include <string>
#include <iostream>
using namespace std;

struct Node
{
    string name;
    Node *link;
};
typedef Node* NodePtr;

NodePtr listPtr, tempPtr;

void insert(string name, int n)
{

    NodePtr temp1 = new Node();
    temp1->name = name;
    temp1->link = NULL;
    if(n == 1){
        temp1->link = listPtr;
        listPtr = temp1;
        return;
    }
    NodePtr temp2 = listPtr;
    for(int i = 0; i < n; i++){
        temp2 = temp2->link;
    }
    temp1->link = temp2->link;
    temp2->link = temp1;
}

void print()
{
    NodePtr temp = listPtr;
    while(temp != NULL)
    {
        cout << temp->name << endl;
        temp = temp->link;
    }
}

/*
 *
 */

int main(int argc, char** argv){
    listPtr = new Node;
    listPtr->name = "Emily";

    tempPtr = new Node;
    tempPtr->name = "James";
    listPtr->link = tempPtr;

    tempPtr->link = new Node;
    tempPtr = tempPtr->link;
    tempPtr->name = "Joules";
    tempPtr->link = NULL;

    print();
    insert("Joshua", 2);
    cout << endl;
    print();

    return 0;
}
for(int i = 0; i < n; i++){
    temp2 = temp2->link;
}

如果n=2並且鏈表中有3元素,則在上述循環的末尾,您將位於最后一個節點,然后在下面的末尾添加新節點。

temp1->link = temp2->link;
temp2->link = temp1;

您希望減少運行循環1時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM