在c++中打印链表的元素(参见代码)

To print elements of Link List in c++ (See Code)

本文关键字:代码 元素 c++ 打印 链表      更新时间:2023-10-16

我的问题是,我试图使一个程序,将使节点(链接列表)动态。一切都很好,但是当我在底部尝试使用while循环打印链接列表的元素时:while(ptr->next !=NULL),程序只打印第一个元素。(是的,我在循环中提到了ptr=ptr->next)下面是我的CODE:

struct node {
    int item;
    node *next;
}
;
main() {
    int a,b,c=0;
    node *head,*tail,*ptr, *temp;
    ptr = new node;
    ptr->item = 0;
    ptr->next = NULL;
    head= ptr;
    ptr->next=tail;
    for (int i=0;1;i++) {
        cout<<" Enter 1 if u want to make another noden Enter 2 to stop making nodesn";
        cin>>a;
        if(a==1) {
            if(c!=0) {
                ptr = new node;
                cout<<"Enter new element at the new node:n";
                cin>>b;
                ptr->item = b;
                ptr->next = NULL;
                tail = ptr;
            }
            if(c==0) {
                ptr = new node;
                cout<<"Enter new element at the new node:n";
                cin>>b;
                ptr->item = b;
                head->next= ptr;
                ptr->next = NULL;
                tail = ptr;
                c++;
            }
        } else if(a==2) {
            break;
        }
    }
    ptr=head;
    while(ptr->next != NULL) {
        ptr=ptr->next;
        cout<<" element: "<<ptr->item<<endl;
    }
}

我的编译器(带有flag -Wall -Wextra -pedantic的g++ 4.8)已经解决了这个问题:

warning: ‘tail’ is used uninitialized in this function [-Wuninitialized]

你正在更新下一个,但有一个未初始化的变量尾部

最初希望将尾部设置为与头部相同的节点。这是因为您希望将元素附加到尾部元素,而不管头部在哪里。这也消除了计算是否添加了一个节点(变量c)的复杂性,并消除了条件分支(其中代码非常相似:参见DRY)

向链表尾部添加元素的过程如下:

  1. 填充新元素,将其next设置为NULL
  2. 将尾元素指向新元素的旁边。
  3. 将新元素设置为尾部

尝试使用这个

struct node {
    int item;
    node *next;
};
main() {
    int input;
    node *head,*tail,*ptr;
    ptr = new node;
    ptr->item = 0;
    ptr->next = NULL;
    head = ptr;
    tail = ptr;
    while(true) {
        cout<<" Enter 1 if u want to make another noden Enter 2 to stop making nodesn";
        cin>>input;
        cin.clear();
        if(input==1) {
            ptr = new node;
            cout<<"Enter new element at the new node:n";
            cin>>input;
            cin.clear();
            ptr->item = input;
            tail->next= ptr;
            ptr->next = NULL;
            tail = ptr;
        } else if(input==2) {
            break;
        }
    }
    ptr=head;
    while(ptr->next != NULL) {
        ptr=ptr->next;
        cout<<" element: "<<ptr->item<<endl;
    }
}
相关文章: