본문 바로가기

알고리즘/해커랭크

[해커랭크] Compare two linked lists

문제링크 : www.hackerrank.com/challenges/compare-two-linked-lists/problem

 

Compare two linked lists | HackerRank

Compare the data in two linked lists node by node to see if the lists contain identical data.

www.hackerrank.com

 

import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;

public class Solution {

    static class SinglyLinkedListNode {
        public int data;
        public SinglyLinkedListNode next;

        public SinglyLinkedListNode(int nodeData) {
            this.data = nodeData;
            this.next = null;
        }
    }

    static class SinglyLinkedList {
        public SinglyLinkedListNode head;
        public SinglyLinkedListNode tail;

        public SinglyLinkedList() {
            this.head = null;
            this.tail = null;
        }

        public void insertNode(int nodeData) {
            SinglyLinkedListNode node = new SinglyLinkedListNode(nodeData);

            if (this.head == null) {
                this.head = node;
            } else {
                this.tail.next = node;
            }

            this.tail = node;
        }
    }

    public static void printSinglyLinkedList(SinglyLinkedListNode node, String sep, BufferedWriter bufferedWriter) throws IOException {
        while (node != null) {
            bufferedWriter.write(String.valueOf(node.data));

            node = node.next;

            if (node != null) {
                bufferedWriter.write(sep);
            }
        }
    }

    // Complete the compareLists function below.

    /*
     * For your reference:
     *
     * SinglyLinkedListNode {
     *     int data;
     *     SinglyLinkedListNode next;
     * }
     *
     */
    static boolean compareLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) {
        while(head1!=null && head2!=null){
            if(head1.data != head2.data) return false;
            head1 = head1.next;
            head2 = head2.next;
        }
        return (head1==null && head2==null);

    }

    private static final Scanner scanner = new Scanner(System.in);

'알고리즘 > 해커랭크' 카테고리의 다른 글

[해커랭크] Merge two sorted linked lists  (0) 2021.01.14
[해커랭크] Get Node Value  (0) 2021.01.14
[해커랭크] Reverse a linked list  (0) 2021.01.13
[해커랭크] Print in Reverse  (0) 2021.01.13
[해커랭크] Delete a Node  (0) 2021.01.13