【Hackerrank】Insert a node into a sorted doubly linked list

You’re given the pointer to the head node of a sorted doubly linked list and an integer to insert into the list. The data in the nodes of the list are in ascending order. Create a node and insert it into the appropriate position in the list. The head node might be NULL to indicate that the list is empty.

Input Format
You have to complete the Node* SortedInsert(Node* head, int data) method which takes two arguments - the head of the sorted, doubly linked list and the value to insert. You should NOT read any input from stdin/console.

Output Format
Create a node with the given data and insert it into the given list, making sure that the new list is also sorted. Then return the head node of the updated list. Do NOT print anything to stdout/console.

Sample Input

NULL , data = 2
NULL <– 2 <–> 4 <–> 6 –> NULL , data = 5

Sample Output

NULL <-- 2 --> NULL
NULL <-- 2 <--> 4 <--> 5 <--> 6 --> NULL

Explanation
1. We have an empty list, 2 is inserted.
2. Data 5 is inserted such as list remains sorted.


#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
using namespace std;
struct Node
{
	int data;
	Node* next;
	Node* prev;
};/*
    Insert Node in a doubly sorted linked list 
    After each insertion, the list should be sorted
   Node is defined as
   struct Node
   {
     int data;
     Node *next;
     Node *prev
   }
*/
Node* SortedInsert(Node *head,int data)
{
    // Complete this function
   // Do not write the main method. 
    Node *cur = new Node();
    cur->data = data;
    cur->next = cur->prev = NULL;
    if(head == NULL)
        return cur;
    Node *pos = head;
    while(pos != NULL && pos->data <= data)
        pos = pos->next;
    if(pos == NULL)
    {
        Node *tail = head;
        while(tail->next != NULL)
            tail = tail->next;
        tail->next = cur;
        cur->prev = tail;
        return head;
    }
    Node *pre = pos->prev;
    if(pre == NULL)
    {
        cur->next = head;
        head->prev = cur;
        return cur;
    }
    pre->next = cur;
    cur->prev = pre;
    cur->next = pos;
    pos->prev = cur;
    return head;
}void Print(Node *head) {
	if(head == NULL) return;
	while(head->next != NULL){ cout<<head->data<<" "; head = head->next;}
	cout<<head->data<<" ";
	while(head->prev != NULL) { cout<<head->data<<" "; head = head->prev; }
	cout<<head->data<<"\n";
}
int main()
{
	int t; cin>>t;
	Node *head = NULL;
	while(t--) {
	   int n; cin>>n;
           head = NULL;
	   for(int i = 0;i<n;i++) {
		   int x; cin>>x;
		   head = SortedInsert(head,x);
	       Print(head);
	   }
	}
}


你可能感兴趣的:(链表,hackerrank)