Inserting a node into a sorted doubly linked list

Sarin Nanda

I am trying to enter a new node in a sorted linked list. I do not know what is wrong in this code.

Node* SortedInsert(Node *head,int data)
{
    struct Node *temp=head,*p=NULL;
    struct Node *newNode=(struct Node*)malloc(sizeof(struct Node));
    newNode->data=data;
    newNode->next=NULL;
    newNode->prev=NULL;
    if(!head){
        return newNode;
    }

    while((data>=(temp->data)) && temp!=NULL){
        p=temp;
        temp=temp->next;
    }
    if(temp==NULL){
        p->next=newNode;
        newNode->prev=p;
        return head;
    }
    if(p==NULL){
        head->prev=newNode;
        newNode->next=head;
        return newNode;
    }

    p->next=newNode;
    newNode->prev=p;
    newNode->next=temp;
    temp->prev=newNode;

    return head;
}
Eelke

The line

while((data>=(temp->data)) && temp!=NULL){

should read

while(temp!=NULL && (data>=(temp->data))){

You need to test temp is not NULL first otherwise you might do an invalid read which can cause an access violation.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Inserting a node into a sorted doubly linked list

From Dev

Sorted doubly linked list and inserting values

From Dev

Inserting Node in a Sorted linked list

From Dev

Inserting a node at the end of a doubly linked list

From Dev

Insert Node in a Sorted Doubly linked list

From Dev

Sorted Doubly Linked List

From Dev

Inserting a node in a pre sorted linked list

From Dev

Inserting a node before a given node in doubly linked list

From Dev

Inserting a new node into a doubly linked list after a given node

From Dev

Deleting a node in a doubly linked list

From Dev

alphabetically sorted insertion into doubly-linked list

From Dev

Inserting Node into a Linked List

From Dev

Inserting an element into an already sorted linked list

From Dev

Linked list insert a node in sorted linked list

From Dev

How to append a node in a doubly linked list in Java?

From Dev

Doubly linked list, add node in-order

From Dev

Removing/undoing the only node in a doubly linked list

From Dev

Python Doubly Linked List Node Removal

From Dev

Node deletion in a doubly-linked list

From Dev

Doubly Linked List node's next is private

From Dev

Doubly linked list adding node at nth location

From Dev

How to append a node in a doubly linked list in Java?

From Dev

delete node in doubly linked list (Data Structures)

From Dev

search for a node at a given position doubly linked list

From Dev

Java - Delete Node From Doubly Linked List

From Dev

python doubly linked list - insertAfter node

From Dev

inserting node to linked list in c

From Dev

inserting node at beginning of linked list

From Dev

Inserting a node at the end of linked list

Related Related

HotTag

Archive