How to change linked list function

时间:2019-06-01 14:03:05

标签: c++ linked-list

I want to change linked list in way to insert a new node which is sum of previous and next node.

Linked list: 1,2,3,4,5
New linked list: 1,3,2,5,3,7,4,9,5

I did some coding, but im not getting good result.

void check(){

    Node *p = head;
    Node *new_node = new Node;
    while (p->next != NULL){
        new_node->data = p->data + p->next->data;
        new_node->next = p->next;  
        p->next = new_node;
        p =p->next->next; 
}

Im getting

1
9
5

as a result.

1 个答案:

答案 0 :(得分:1)

(在drescherjm和user10933809的评论中得到答复。)

Node *new_node = new Node;应该在while循环内。

由于每次都重复使用同一新节点,因此其值将设置为最终总和(9),并且其next指针指向最后一个节点(5)。所有其他节点的next指针都指向新节点,因此您将具有以下结构:

head -> 1 --\ 
        2 -\ \
            ---> 9 -> 5
        3 -/ /
        4 --/ 

指向节点2、3和4的指针丢失,因此无法访问。