Пример #1
0
  public int search(Object p) {
    int index = 0;
    boolean flag = false;
    temp = back;
    ListNode temp2 = new ListNode(p, null);

    if (back == null) {
      return -1;
    }
    // else if case

    else {
      while (temp.getNext() != null && flag == false) {
        if (temp.getValue() == temp2.getValue()) {
          flag = true;
        } else {
          temp = temp.getNext();
          index++;
        }
      }

      if (flag) {
        return index;
      } else {
        return -1;
      }
    }
  }
Пример #2
0
 /**
  * 打印链表
  *
  * @param head 头指针
  */
 public static void printList(ListNode head) {
   ListNode current = head;
   while (current != null) {
     System.out.print(current.getValue() + "、");
     current = current.getNext();
   }
   System.out.println();
 }
Пример #3
0
  /**
   * 合并两个链表
   *
   * @param head1 链表1
   * @param head2 链表2
   * @return
   */
  public static ListNode mergeList(ListNode head1, ListNode head2) {
    ListNode head = null; // 合并后的头指针

    // 如果有一个为空,则为另一个链表
    if (head1 == null) head = head2;
    if (head2 == null) head = head1;

    // 两个都不为空
    if (head1 != null && head2 != null) {
      // node_1和node_2是用于遍历
      ListNode node_1 = head1;
      ListNode node_2 = head2;
      if (node_1.getValue() < node_2.getValue()) {
        head = node_1;
        head.setNext(mergeList(node_1.getNext(), node_2));
      } else {
        head = node_2;
        head.setNext(mergeList(node_1, node_2.getNext()));
      }
    }
    return head;
  }