将链接列表list_1的第一个元素添加为链接列表list_2的最后一个元素,并将其从list_1中删除

时间:2018-11-14 14:38:38

标签: java

例如,如果list_2 = {5, 6, 7, 8}list_1 = {9, 10, 11, 12},则: Addtolist2(list_2, list_1)将更改list_2 to {5, 6, 7, 8, 9},并将list_1更改为{10, 11, 12}。请注意,您不应使用此方法创建新列表。

public class ListNode {
    int data;
    ListNode next;
}

public class List {
     ListNode header;
}

这是我尝试过的:

public static void Addtolist2(list_2, List_1) {
    ListNode p = l2.header.next;

    while(p != null) {
        p = p.next;
    }

    p = l1.header.next;
    ListNode q = l1.header.next;

    if (l1.header.next.next != null) {
        q = l1.header.next.next;
    }
}

3 个答案:

答案 0 :(得分:0)

List<Integer> lst1 = new ArrayList<>(Arrays.asList(5, 6, 7, 8));
List<Integer> lst2 = new ArrayList<>(Arrays.asList(9, 10, 11, 12));
System.out.println("lst1 = " + lst1 + " lst2 = " + lst2);
Integer moved = lst2.get(0);
lst2.remove(0);
lst1.add(moved);
System.out.println("lst1 = " + lst1 + " lst2 = " + lst2);

答案 1 :(得分:0)

public class MainClass
{
public static void main(String[] args)
{
    LinkedList<Integer> list1 = new LinkedList<Integer>();
    list1.add(5);
    list1.add(6);
    list1.add(7);
    list1.add(8);

    LinkedList<Integer> list2 = new LinkedList<Integer>();
    list2.add(9);
    list2.add(10);
    list2.add(11);
    list2.add(12);

    Integer element = list2.getFirst();
    list1.addLast(element);
    list2.removeFirst();

    System.out.println("First List:");
    System.out.print(list1);

    System.out.println();
    System.out.println("Second List: ");
    System.out.print(list2);
}
}

答案 2 :(得分:0)

也许尝试这样的事情(您可能需要更改一些内容)

public static void Addtolist2(List list2, List list1) {
    // Find last node in list2
    ListNode lastEl = list2.header;
    while(lastEl != null) {
        lastEl = lastEl.next;
    }

    // Take the first element of list1
    ListNode firstEl = list1.header;

    // Add new element to list2 in last
    ListNode newEl = new ListNode();
    newEl.data = firstEl.data;
    lastEl = newEl;

    // Remove first element of list1 (replace with second)
    list1.header = firstEl.next;
}