본문 바로가기

알고리즘/해커랭크

[해커랭크] Delete a Node

문제링크: www.hackerrank.com/challenges/delete-a-node-from-a-linked-list/problem

 

Delete a Node | HackerRank

Delete a node from the linked list and return the head.

www.hackerrank.com

한번에 통과하지 못해서 예외를 생각하고 position이 0일때 head.next를 리턴하는걸 추가했다.

항상 꼼꼼히 생각해야겠다.

그리고 자료구조 문제를 풀고 다른사람 코드를 보면 재귀로 푼 코드가 상위에 자주 보인다. 깔끔한 코드인 것 같다. 

 

-다른사람풀이

Node Delete(Node head, int poisition){

    if (position == 0) return head.next;

    head.next = Delete(head.next, position-1);

    return head;

}

-내 풀이

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
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 deleteNode function below.

    /*
     * For your reference:
     *
     * SinglyLinkedListNode {
     *     int data;
     *     SinglyLinkedListNode next;
     * }
     *
     */
    static SinglyLinkedListNode deleteNode(SinglyLinkedListNode head, int position) {
        if(position==0)return head.next;
        
        SinglyLinkedListNode searchKey = head;
        for(int i=0;i<position-1;i++){
            searchKey= searchKey.next;    
        }
        if(searchKey.next!=null)
            searchKey.next = searchKey.next.next;
        else
            searchKey.next = null;
        return head;

    }

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