Doubly linked list insertion

problem:

    Given to a doubly linked list sorted, to insert an element.

solution:

struct ListNode {
    int val;
    ListNode *prev;
    ListNode *next;
};

int insert(ListNode *head, int value)
{
    ListNode *cur;
    ListNode *next;
    for (cur = head; (next = cur->next) != NULL; cur = next)
    {
        if (next->val == value)
            return 0;
        if (next->val > value)
            break;
    }

    ListNode *newNode = new ListNode;
    newNode->val = value;

    newNode->next = next;
    cur->next = newNode;
    if (cur != head)
        newNode->prev = cur;
    else
        newNode->prev = NULL;
    if (next != NULL)
        next->prev = newNode;
    else
        head->prev = newNode;
    return 1;
}

Two things to note:

1. Declare a header node head, wherein the head-> prev points to a linked list of the last node, head-> next points to a linked list of the first node.

2. When the list of elements and insert elements repeated insertion operation is not performed.

 

reference:

"C and pointer"

Reproduced in: https: //www.cnblogs.com/gattaca/p/4748738.html

Guess you like

Origin blog.csdn.net/weixin_34238633/article/details/93401955