码迷,mamicode.com
首页 > 其他好文 > 详细

[Hackerrank]Inserting a Node Into a Sorted Doubly Linked List

时间:2017-11-02 18:22:04      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:ted   ext   思路   inpu   col   linked   reference   pointer   nbsp   

Given a reference to the head of a doubly-linked list and an integer, data, create a new Node object having data value data and insert it into a sorted linked list.

在双向升序链表中插入一个数,并且不能破环链表升序的结构;

 

思路:递归

/*
  Insert Node at the end of a linked list 
  head pointer input could be NULL as well for empty list
  Node is defined as 
  class Node {
     int data;
     Node next;
     Node prev;
  }
*/

Node SortedInsert(Node head,int data) {
    Node newNode = new Node();
    newNode.data = data;
    if (head==null)
        return newNode;                 //如果是空表则返回新的节点
    else if (data<=head.data){
        head.prev = newNode;        //如果插入的元素比头节点元素小,就插在头节点
        newNode.next = head;        //前面
        return newNode;
    }
    else {
        Node tmp = SortedInsert(head.next,data);
        tmp.prev = head;
        head.next = tmp;
    }
    return head;
}

 

[Hackerrank]Inserting a Node Into a Sorted Doubly Linked List

标签:ted   ext   思路   inpu   col   linked   reference   pointer   nbsp   

原文地址:http://www.cnblogs.com/David-Lin/p/7773112.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!