public ListNode mergeKLists(ArrayList<ListNode> lists) {

    if (lists.size() == 0) return null;

    PriorityQueue<ListNode> q =
        new PriorityQueue<ListNode>(
            lists.size(),
            new Comparator<ListNode>() {

              public int compare(ListNode a, ListNode b) {
                if (a.val > b.val) return 1;
                else if (a.val == b.val) return 0;
                else return -1;
              }
            });

    for (ListNode i : lists) if (i != null) q.add(i);

    ListNode head = new ListNode(-1);
    ListNode pre = head;

    while (q.size() != 0) {

      ListNode temp = q.poll();
      pre.next = temp;

      if (temp.next != null) q.add(temp.next);

      pre = pre.next;
    }

    return head.next;
  }
  public ListNode mergeKLists(ArrayList<ListNode> lists) {
    if (lists == null || lists.isEmpty()) return null;
    ListNode head = new ListNode(0);
    ListNode p = head;

    PriorityQueue<ListNode> queue =
        new PriorityQueue<ListNode>(
            lists.size(),
            new Comparator<ListNode>() {

              @Override
              public int compare(ListNode o1, ListNode o2) {
                return o1.val - o2.val;
              }
            });
    for (ListNode n : lists) {
      if (n != null) {
        queue.offer(n);
      }
    }

    while (!queue.isEmpty()) {
      ListNode n = queue.poll();
      p.next = n;
      p = p.next;
      if (n.next != null) {
        queue.offer(n.next);
      }
    }

    return head.next;
  }
Beispiel #3
0
  public ListNode removeNthFromEnd(ListNode head, int n) {
    // Start typing your Java solution below
    // DO NOT write main() function
    if (head == null) {
      return null;
    }

    ListNode tail = head;
    int i = 0;
    for (; i < n && tail != null; ++i) {
      tail = tail.next;
    }

    if (tail == null && i < n) {
      return null;
    }

    ListNode nth = head;
    ListNode pHead = new ListNode(0);
    pHead.next = head;
    ListNode prev = pHead;
    while (tail != null) {
      prev = nth;
      nth = nth.next;
      tail = tail.next;
    }

    // remove nth from end
    prev.next = nth.next;

    return pHead.next;
  }
  public ListNode deleteDuplicates(ListNode head) {
    if (head == null) {
      return null;
    }

    Set<Integer> valToRemove = new HashSet<Integer>();
    ListNode cur = head;
    while (cur != null) {
      if (cur.next != null && cur.val == cur.next.val) {
        valToRemove.add(cur.val);
      }
      cur = cur.next;
    }
    ListNode fake = new ListNode(0);
    fake.next = head;
    cur = fake;
    while (cur.next != null) {
      if (valToRemove.contains(cur.next.val)) {
        cur.next = cur.next.next;
        continue;
      }
      cur = cur.next;
    }
    return fake.next;
  }
Beispiel #5
0
 public void padList(ListNode head, int len) {
   for (int i = 0; i < len; i++) {
     ListNode newNode = new ListNode(0);
     newNode.next = head;
     head = newNode;
   }
 }
 public static ListNode reverseKGroup(ListNode head, int k) {
   if (head == null || head.next == null || k < 2) {
     return head;
   }
   LinkedList<ListNode> l = new LinkedList<ListNode>();
   int count = 0;
   ListNode pre = new ListNode(0);
   ListNode temp = pre;
   while (head != null) {
     if (count++ < k) {
       ListNode t = new ListNode(head.val);
       l.push(t);
       head = head.next;
     }
     if (count >= k) {
       count = 0;
       while (!l.isEmpty()) {
         temp.next = l.pop();
         temp = temp.next;
       }
     }
   }
   while (!l.isEmpty()) {
     temp.next = l.pollLast();
     temp = temp.next;
   }
   return pre.next;
 }
  public static ListNode NAfterMMore(ListNode head, int m, int n) {
    if (head == null || head.next == null || n == 0) return head;

    ListNode p = head, previous = null;
    int count = 0;

    while (p != null) {
      count = 0;
      while (count < m) {
        count++;
        previous = p;
        p = p.next;
      }

      count = 0;

      while (count < n && p != null) {
        count++;
        p = p.next;
      }
      previous.next = p;
      previous = previous.next;
      // p = p == null ? null : p.next;
    }
    return head;
  }
Beispiel #8
0
 public ListNode deleteDuplicates(ListNode a) {
   ListNode temp = a;
   LinkedHashMap<Integer, Integer> map = new LinkedHashMap<Integer, Integer>();
   int i = 0;
   while (temp != null) {
     if (map.get(temp.val) == null) {
       map.put(temp.val, 1);
     } else {
       map.put(temp.val, map.get(temp.val) + 1);
     }
     temp = temp.next;
   }
   System.out.println(map);
   Iterator<Integer> it = map.keySet().iterator();
   ListNode root = null;
   ListNode root1 = null;
   while (it.hasNext()) {
     int x = it.next();
     if (map.get(x) == 1) {
       if (root == null) {
         root = new ListNode(x);
         root1 = root;
       } else {
         ListNode node = new ListNode(x);
         root1.next = node;
         root1 = node;
       }
     }
   }
   return root;
 }
Beispiel #9
0
  public ListNode mergeList(ListNode head1, ListNode head2) {
    if (head1 == null) return head2;
    if (head2 == null) return head1;
    ListNode dummy = new ListNode(-1);
    ListNode p = dummy;

    ListNode p1 = head1;
    ListNode p2 = head2;
    while (p1 != null && p2 != null) {
      p.next = p1;
      p1 = p1.next;
      p = p.next;

      p.next = p2;
      p2 = p2.next;
      p = p.next;
    }

    if (p1 == null) {
      p.next = p2;
    }
    if (p2 == null) {
      p.next = p1;
    }
    return dummy.next;
  }
Beispiel #10
0
  /* Helpers */
  private static InputArgs input() throws IOException {
    System.out.println("2.2 Return Kth to Last");

    // read K
    System.out.print("Please input K: ");
    Scanner sc = new Scanner(System.in);
    int k = sc.nextInt();

    // read number of nodes
    System.out.println();
    System.out.print("Please input the number of nodes in the linked list: ");
    int n = sc.nextInt();

    // read linked list
    System.out.println();
    System.out.print("Please input value of nodes (seperate by space, e.g., 1 2 3): ");

    ListNode dummy = new ListNode(0);
    ListNode pre = dummy;
    for (int i = 0; i < n; i++) {
      ListNode cur = new ListNode(sc.nextInt());
      pre.next = cur;
      pre = cur;
    }

    return new InputArgs(k, dummy.next);
  }
  /**
   * @param head: The first node of linked list.
   * @return: a tree node
   */
  public TreeNode sortedListToBST(ListNode head) {
    // write your code here

    if (head == null) {
      return null;
    }

    ListNode current = head;
    int count = 0;
    while (current != null) { // 遍历单链表
      count++;
      current = current.next;
    }

    ListNode middle = head, prev = null;
    for (int i = 0; i < count / 2; i++) {
      prev = middle;
      middle = middle.next;
    }
    TreeNode root = new TreeNode(middle.val);

    if (middle == head) { // 说明链表长度为1,直接输出
      return root;
    }

    prev.next = null;
    root.left = sortedListToBST(head);
    root.right = sortedListToBST(middle.next);

    return root;
  }
 public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
   addNode = new ListNode(l1.val + l2.val);
   ListNode travel = addNode;
   ListNode l1Travel = l1;
   ListNode l2Travel = l2;
   int a;
   int b;
   int over = 0;
   while ((l1Travel.next != null) || (l2Travel.next != null) || over != 0) {
     a = l1Travel.next == null ? 0 : l1Travel.next.val;
     b = l2Travel.next == null ? 0 : l2Travel.next.val;
     over = over + a + b;
     travel.next = new ListNode((over) % 10);
     travel = travel.next;
     over = (over) / 10;
     if (l1Travel.next != null) {
       l1Travel = l1Travel.next;
     }
     if (l2Travel.next != null) {
       l2Travel = l2Travel.next;
     }
   }
   travel.next = null;
   return addNode;
 }
Beispiel #13
0
 public ListNode swapPairs(ListNode head) {
   if ((head == null) || (head.next == null)) return head;
   ListNode n = head.next;
   head.next = swapPairs(head.next.next);
   n.next = head;
   return n;
 }
Beispiel #14
0
  public ListNode rotateRight(ListNode head, int k) {
    // corner case
    if (head == null || head.next == null) {
      return head;
    }

    // get length and move one pointer to the end of the list
    int count = 1;
    ListNode node = head;
    while (node != null && node.next != null) {
      count++;
      node = node.next;
    }
    k = k % count;

    int step = count - k - 1;

    ListNode temp = head;
    for (int i = 0; i < step; i++) {
      temp = temp.next;
    }

    // System.out.println(right.val);
    // System.out.println(right.next);

    node.next = head;
    // System.out.println(right.next);
    // ListNode right = temp.next;

    ListNode right = temp.next;
    temp.next = null;
    return right;
  }
Beispiel #15
0
  public ListNode rotateRight(ListNode head, int k) {
    if (head == null || head.next == null || k == 0) return head;
    ListNode p = new ListNode(-1);
    ListNode p1 = head;
    ListNode p2 = head;
    ListNode temp = head;
    int len = 0;

    while (temp != null) {
      len++;
      temp = temp.next;
    }

    k %= len;
    if (k == 0) return head;

    for (int i = 0; i < k; i++) {
      p1 = p1.next;
    }
    while (p1.next != null) {
      p1 = p1.next;
      p2 = p2.next;
    }

    p = p2.next;
    p1.next = head;
    p2.next = null;

    return p;
  }
 public ListNode mergeKLists(ListNode[] lists) {
   ListNode sentinel = new ListNode(0);
   ListNode current = sentinel;
   PriorityQueue<ListNode> heap =
       new PriorityQueue<>(
           (e1, e2) -> {
             if (e1.val > e2.val) {
               return 1;
             } else if (e1.val < e2.val) {
               return -1;
             } else {
               return 0;
             }
           });
   for (ListNode node : lists) {
     if (node != null) {
       heap.add(node);
     }
   }
   while (heap.isEmpty() == false) {
     ListNode nodeWithMinValue = heap.poll();
     current.next = nodeWithMinValue;
     nodeWithMinValue = nodeWithMinValue.next;
     if (nodeWithMinValue != null) {
       heap.add(nodeWithMinValue);
     }
   }
   return sentinel.next;
 }
Beispiel #17
0
  public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    ListNode l1c = l1;
    ListNode l2c = l2;

    ListNode head = new ListNode(-100);
    ListNode r = head;
    while (l1c != null && l2c != null) {
      if (l1c.val > l2c.val) {
        head.next = l2c;
        l2c = l2c.next;
        head = head.next;
      } else {
        head.next = l1c;
        l1c = l1c.next;
        head = head.next;
      }
    }

    if (l1c == null) {
      head.next = l2c;
    }

    if (l2c == null) {
      head.next = l1c;
    }

    return r.next;
  }
  public static ListNode[] SecondTry(ListNode l1, ListNode l2) {
    if (l1 == null || l2 == null) {
      return new ListNode[] {l1 == null ? l2 : l1, l1 == null ? l2 : l1};
    }

    ListNode[] res = new ListNode[2];
    ListNode newHead = new ListNode(), head1 = new ListNode(), head2 = new ListNode();
    ListNode p = newHead, p1 = l1, p2 = l2;
    head1.next = p1;
    head2.next = p2;

    while (p1 != null && p2 != null) {
      p.next = p1;
      p = p.next;
      head1.next = p1.next;
      p1 = p1.next;

      p.next = p2;
      p = p.next;
      head2.next = p2.next;
      p2 = p2.next;
    }
    p.next = null;
    res[0] = newHead.next;
    res[1] = head2.next;

    return res;
  }
  /**
   * @param ListNode head is the head of the linked list
   * @return: ListNode head of the linked list
   */
  public static ListNode deleteDuplicates(ListNode head) {
    // write your code here
    if (head == null || head.next == null) {
      return head;
    }

    ListNode curt = new ListNode(0);
    ListNode ret = curt;

    while (head != null && head.next != null) {
      if (head.val != head.next.val) {
        curt.next = new ListNode(head.val);
        curt = curt.next;
        head = head.next;
      } else {
        while (head.next != null && head.val == head.next.val) {
          head = head.next;
        }
        head = head.next;
      }
    }
    if (head != null) {
      curt.next = new ListNode(head.val);
    }
    return ret.next;
  }
Beispiel #20
0
  private ListNode removeNode(ListNode head, int pos) {
    if (pos == 0) {
      return head.next;
    }
    if (pos == 1) {
      return head.next;
    } else {
      int count = 1;
      ListNode previous = head;
      ListNode next = head.next;

      while (next != null && count < pos - 1) {
        previous = next;
        next = next.next;
        count++;
      }

      if (next == null) {
        previous.next = null;
      } else {
        previous.next = next.next;
      }

      return head;
    }
  }
 public ListNode deleteDuplicates(ListNode head) {
   if (head == null) {
     return head;
   }
   ListNode dummy = new ListNode(0);
   dummy.next = head;
   ListNode prev = dummy;
   boolean dup = false;
   while (head != null) {
     if (head.next != null && head.val == head.next.val) {
       head = head.next;
       dup = true;
     } else if (head.next == null) {
       if (dup) {
         prev.next = null;
       }
       head = head.next;
     } else if (head.val != head.next.val) {
       if (dup) {
         head = head.next;
         prev.next = head;
         dup = false;
       } else {
         prev = head;
         head = head.next;
       }
     }
   }
   return dummy.next;
 }
 public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
   ListNode dummy = new ListNode(0);
   ListNode cur = dummy;
   while (l1 != null || l2 != null) {
     if (l1 != null && l2 != null) {
       if (l1.val <= l2.val) {
         cur.next = l1;
         l1 = l1.next;
       } else {
         cur.next = l2;
         l2 = l2.next;
       }
       cur = cur.next;
     } else if (l1 == null && l2 != null) {
       cur.next = l2;
       l2 = l2.next;
       cur = cur.next;
     } else if (l1 != null && l2 == null) {
       cur.next = l1;
       l1 = l1.next;
       cur = cur.next;
     }
   }
   return dummy.next;
 }
 public static ListNode reverseKNodes(ListNode head, int k) {
   // Start with head
   ListNode current = head;
   // last node after reverse
   ListNode prevTail = null;
   // first node before reverse
   ListNode prevCurrent = head;
   while (current != null) {
     // loop for reversing K nodes
     int count = k;
     ListNode tail = null;
     while (current != null && count > 0) {
       ListNode next = current.getNext();
       current.setNext(tail);
       tail = current;
       current = next;
       count--;
     }
     // reversed K Nodes
     if (prevTail != null) {
       // Link this set and previous set
       prevTail.setNext(tail);
     } else {
       // We just reversed first set of K nodes, update head point to the Kth Node
       head = tail;
     }
     // save the last node after reverse since we need to connect to the next set.
     prevTail = prevCurrent;
     // Save the current node, which will become the last node after reverse
     prevCurrent = current;
   }
   return head;
 }
Beispiel #24
0
 // fail to solve the problem
 // This is very basic and important!
 public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
   // only one statement is enough to solve 3 condition
   // cause linklist is connected, I don't need to insert rest of the node anymore
   if (l1 == null || l2 == null) return l1 == null ? l2 : l1;
   // the head node is specil, need seperate initiate.
   ListNode head = null;
   if (l1.val <= l2.val) {
     head = l1;
     l1 = l1.next;
   } else {
     head = l2;
     l2 = l2.next;
   }
   ListNode temp = head;
   // in while loop, temp.next = smallvalue; l1 = l1.next; temp = temp.next;
   while (l1 != null && l2 != null) {
     if (l1.val <= l2.val) {
       temp.next = l1;
       l1 = l1.next;
     } else {
       temp.next = l2;
       l2 = l2.next;
     }
     ;
     temp = temp.next;
   }
   // finally, we find the non-null node add it to the rear of l3
   // cause linklist is connected, I don't need to insert rest of the node anymore
   temp.next = l1 == null ? l2 : l1;
   return head;
 }
 public ListNode mergeKLists(ArrayList<ListNode> lists) {
   if (lists == null || lists.isEmpty()) return null;
   PriorityQueue<ListNode> heap =
       new PriorityQueue<ListNode>(
           lists.size(),
           new Comparator<ListNode>() {
             public int compare(ListNode o1, ListNode o2) {
               return o1.data > o2.data ? 1 : (o1.data < o2.data ? -1 : 0);
             }
           });
   for (ListNode node : lists) {
     if (node != null) {
       heap.add(node);
     }
   }
   ListNode head = null, cur = null;
   while (!heap.isEmpty()) {
     if (head == null) {
       head = heap.poll();
       cur = head;
     } else {
       cur.next = heap.poll();
       cur = cur.next;
     }
     if (cur.next != null) {
       heap.add(cur.next);
     }
   }
   return head;
 }
Beispiel #26
0
  public void reorderList(ListNode head) {
    if (head == null || head.next == null || head.next.next == null) {
      return;
    }
    ListNode oneStep = head;
    ListNode twoStep = head;

    while (twoStep != null && twoStep.next != null) {
      twoStep = twoStep.next.next;
      oneStep = oneStep.next;
    }

    ListNode half = oneStep.next;
    oneStep.next = null;

    Stack<ListNode> stack = new Stack<ListNode>();
    while (half != null) {
      stack.push(half);
      half = half.next;
    }

    ListNode tmp = head;

    while (head != null) {
      ListNode oldRight = head.next;
      if (stack.empty()) {
        break;
      }
      head.next = stack.pop();
      head.next.next = oldRight;
      head = oldRight;
    }
    head = tmp;
  }
  public static boolean isPalindrome_good(ListNode head) {
    if (head == null || head.next == null) {
      return true;
    }
    ListNode fast = head;
    ListNode slow = head;
    while (fast.next != null && fast.next.next != null) {
      slow = slow.next;
      fast = fast.next.next;
    }

    ListNode newhead = slow.next;
    ListNode pre = null;
    while (newhead != null) {
      ListNode temp = newhead.next;
      newhead.next = pre;
      pre = newhead;
      newhead = temp;
    }
    while (pre != null) {
      if (pre.val != head.val) {
        return false;
      }
      pre = pre.next;
      head = head.next;
    }
    return true;
  }
Beispiel #28
0
  /*
  Solution 2
  	Did not use additional space, each time encounter the first unique value node,
  	traversal the rest of the list to delete the same value's nodes.
  Assumption:
  	None.
  Time complexity: O(n^2)
  Space Complexity: O(1)
  */
  private static ListNode RemoveDups2(ListNode head) {
    if (head == null) return head;

    ListNode pre = head;
    while (pre != null) {
      ListNode pre2 = pre;
      ListNode cur = pre.next;
      int target = pre.val;

      while (cur != null) { // delete the dups in the rest of the list
        if (cur.val == target) {
          pre2.next = cur.next;
          cur = cur.next;
        } else {
          pre2 = cur;
          cur = cur.next;
        }
      }

      // move to next different value's node
      pre = pre.next;
    }

    return head;
  }
 /**
  * @param ListNode l1 is the head of the linked list
  * @param ListNode l2 is the head of the linked list
  * @return: ListNode head of linked list
  */
 public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
   // write your code here
   if (l1 == null && l2 == null) {
     return null;
   }
   ListNode fakeHead = new ListNode(0);
   ListNode curr = fakeHead;
   while (l1 != null && l2 != null) {
     if (l1.val <= l2.val) {
       curr.next = l1;
       l1 = l1.next;
     } else {
       curr.next = l2;
       l2 = l2.next;
     }
     curr = curr.next;
   }
   if (l1 != null) {
     curr.next = l1;
   }
   if (l2 != null) {
     curr.next = l2;
   }
   return fakeHead.next;
 }
  public ListNode removeNthFromEnd(ListNode head, int n) {

    if (head == null || head.next == null) {
      return null;
    }

    ListNode first = head;
    ListNode second = head;

    for (int i = 0; i < n; i++) {
      first = first.next;
      if (first == null) {
        return head.next;
      }
    }

    while (first.next != null) {
      first = first.next;
      second = second.next;
    }

    second.next = second.next.next;

    return head;
  }