链表。如何删除列表中的第一个节点?

时间:2019-08-23 13:22:30

标签: c++

我需要删除原始列表中的节点,该节点的值等于第二个列表中的节点值,然后我需要返回更新的原始列表。我删除了(至少我认为是这样做的)列表中的第一个节点,但是当我调用该函数然后尝试打印更新的列表时,程序会不断打印4个随机数。删除功能适用于所有其他节点,但不适用于第一个节点。

#include<iostream>

using namespace std;

struct Node{
    int x;
    Node* next;
};

Node* createNode(int x){
    Node* node=new Node();
    node->x=x;
    node->next=NULL;
    return node;
}

Node* createList(){
    int i,n;
    Node* head=NULL,*p=NULL;
    cout<<"How many nodes: ";
    cin>>n;
    for(i=0;i<n;i++){
        if(i==0){
            head=new Node();
            p=head;
        }
        else{
            p->next=new Node();
            p=p->next;
        }
        cout<<"Insert value of a node: ";
        cin>>p->x;
    }
    return head;
}

void printList(Node* head){
    cout<<"Values of nodes in a List: "<<endl;
    while(head!=NULL){
        cout<<head->x<<"   ";
        head=head->next;
    }
    cout<<endl;
}

Node* deleteNodes(Node* head,Node* head2){
    Node* temp1=NULL,*p=NULL,*pret=NULL;
    while(head2!=NULL){//1 NULL
        p=head;
        while(p!=NULL){// 1 NULL
            temp1=p->next;
            if(head->x==head2->x){
                pret=head;
                head=pret->next;
                p=head;
                delete pret;
                pret=NULL;
            }
            if(temp1==NULL) break;
            else if(temp1->x==head2->x){
                p->next=temp1->next;
                delete temp1;
            }
            else p=p->next;
        }
        head2=head2->next;
    }
    return head;
}

int main(){
    Node* head=NULL,*head2=NULL;
    head=createList();
    head2=createList();
    cout<<"List 1"<<endl;
    printList(head);
    cout<<"List 2"<<endl;
    printList(head2);
    cout<<"///////////////"<<endl;
    deleteNodes(head,head2);
    printList(head);
    return 0;
}

示例: 原始清单(1,2,3,4,5) 第二名单(1,2,3) 更新列表的预期结果:(4,5) 我的结果:

  

9311504 9306448 9328768 9311504   9311504 9306448 9328768 9311504   9311504 9306448 9328768 9311504   9311504 9306448 9328768 9311504   9311504 9306448 9328768 9311504   9311504 9306448 9328768 9311504   9311504 9306448 9328768 9311504   ...

1 个答案:

答案 0 :(得分:2)

列表的新标题是从函数返回的值,并且您旧的head无效,因为它过去指向的内容已被破坏。

head = deleteNodes(head,head2);,你应该看到自己的梦想成真。

(相关:分配给函数的(非引用)参数对函数外部无效。指针并不特殊。)