THINK FIRST·CODE LATER

← All labs

Merging two sorted linked lists in place

Problem

Write LinkedMerge with your own Node class (no java.util lists). Read two sorted lists (n then n values, twice) and a number k. Then:

  1. merge(a, b) — build one sorted list by relinking the existing nodes (no new Node except one dummy head), stable: on equal values the node from the first list comes first;
  2. fromEnd(head, k) — the k-th node from the end (k = 1 is the last) in one pass, using two references kept k nodes apart; none if the list is shorter.

For the input

4 1 4 6 9
3 2 4 10
2

the program prints

A: 1 -> 4 -> 6 -> 9
B: 2 -> 4 -> 10
Merged: 1 -> 2 -> 4 -> 4 -> 6 -> 9 -> 10
Number 2 from the end: 9

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d10-6-data-1.txt

4 1 4 6 9
3 2 4 10
2
What your program must print for d10-6-data-1.txt
A: 1 -> 4 -> 6 -> 9
B: 2 -> 4 -> 10
Merged: 1 -> 2 -> 4 -> 4 -> 6 -> 9 -> 10
Number 2 from the end: 9

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d10-6-data-1.txt

Windows PowerShell does not understand <:

Get-Content d10-6-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.