【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);
	   }
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值