Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Main{
- static class Node{
- public int data;
- public Node next;
- public Node(int data){
- this.data = data;
- this.next = null;
- }
- @Override
- public String toString() {
- return Integer.toString(data);
- }
- }
- static class SinglyLinkedList {
- public Node head;
- public Node tail;
- public SinglyLinkedList() {
- this.head = null;
- this.tail = null;
- }
- public void insertNodeV1(int nodeData) {
- Node newNode = new Node(nodeData);
- if(this.tail != null && nodeData == this.tail.data) return;
- if (this.head == null) {
- this.head = newNode;
- } else {
- this.tail.next = newNode;
- }
- this.tail = newNode;
- }
- public void insertNodeV2(int nodeData) {
- Node newNode = new Node(nodeData);
- if (this.head == null) {
- this.head = newNode;
- } else {
- Node currentNode = this.head;
- while (currentNode.next != null) {
- currentNode = currentNode.next;
- }
- currentNode.next = newNode;
- }
- }
- private void deleteNext(Node node) {
- node.next = node.next.next;
- }
- public void deleteNode(int position) {
- Node curr = head;
- int curr_position = 0;
- if (position == 0) {
- head = head.next;
- return;
- }
- while (curr_position < position - 1) {
- curr = curr.next;
- curr_position++;
- }
- curr.next = curr.next.next;
- }
- public void mergeLists(SinglyLinkedList first, SinglyLinkedList second){
- Node first_temp = first.head;
- Node second_temp = second.head;
- while(first_temp != null || second_temp != null){
- if(first_temp == null){
- insertNodeV1(second_temp.data);
- second_temp = second_temp.next;
- continue;
- }
- if(second_temp == null){
- insertNodeV1(first_temp.data);
- first_temp = first_temp.next;
- continue;
- }
- if( first_temp.data < second_temp.data) {
- insertNodeV1(first_temp.data);
- first_temp = first_temp.next;
- } else {
- insertNodeV1(second_temp.data);
- second_temp = second_temp.next;
- }
- }
- }
- @Override
- public String toString() {
- StringBuilder stringBuilder = new StringBuilder();
- Node curr = head;
- while(curr != null){
- stringBuilder.append(curr + "->");
- curr = curr.next;
- }
- stringBuilder.append("null");
- return stringBuilder.toString();
- }
- }
- public static void main(String[] args) {
- Scanner reader = new Scanner(System.in);
- SinglyLinkedList first = new SinglyLinkedList();
- SinglyLinkedList second = new SinglyLinkedList();
- SinglyLinkedList result = new SinglyLinkedList();
- int n = reader.nextInt();
- for(int i = 0; i < n; ++i){
- first.insertNodeV1(reader.nextInt());
- }
- int m = reader.nextInt();
- for(int i = 0; i < m; ++i){
- second.insertNodeV1(reader.nextInt());
- }
- result.mergeLists(first, second);
- System.out.println(result);
- Node curr = result.head;
- while(curr != null){
- System.out.printf("%d->", curr.data);
- curr = curr.next;
- }
- System.out.println("null");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement