在合并链表时使用临时节点

时间:2016-08-18 15:12:21

标签: java linked-list

尝试自学链接列表,我偶然发现了合并算法:

Node MergeLists(Node node1, node2)
{
    if(node1 == null)
      return node2;
   else (node2 == null)
      return node1;

   Node head;
   if(node1.data < node2.data)
   {
      head = node1;
      node1 = node1.next;
   else
   {
      head = node2;
      node2 = node2.next;
   }

   Node current = head;
   while((node1 != null) ||( node2 != null))
   {
      if(node1 == null) {
         current.next = node2;
         return head;
      }
      else if (node2 == null) {
         current.next = node1;
         return head;
      }

      if(node1.data < node2.data)
      {
          current.next = node1;
          current = current.next;
          node1 = node1.next;
      }
      else
      {
          current.next = node2;
          current = current.next;
          node2 = node2.next;
      }
   }
   current.next = NULL // needed to complete the tail of the merged list
   return head;

}   

礼貌:https://stackoverflow.com/a/13886252/6630382

虽然我在很大程度上理解逻辑,但我很困惑: 1.为什么我们需要声明“节点当前”?除非我忘记了别名,否则我们不能只使用Node头一直通过吗?

  1. 合并列表是否需要某种先决条件?我们是否必须预先定义一个大小list1 + list2的列表,或者这只是从头开始构建列表?
  2. 非常感谢你!

0 个答案:

没有答案