본문 바로가기
Programming/Data Structure

[Hackerrank] Reversealinkedlist

by 읽고 쓰는 개발자 2020. 12. 2.

www.hackerrank.com/challenges/reverse-a-linked-list/problem

 

Reverse a linked list | HackerRank

Change the links between the nodes of a linked list to reverse it

www.hackerrank.com

package exam.complete;

import exam.SinglyLinkedListNode;

//https://www.hackerrank.com/challenges/reverse-a-linked-list/problem
public class Reversealinkedlist {
    public static void main(String[] args) {
        SinglyLinkedListNode node = new SinglyLinkedListNode(1);
        SinglyLinkedListNode node1 = new SinglyLinkedListNode(2, node);
        SinglyLinkedListNode node2 = new SinglyLinkedListNode(3, node);

        reverse(node);
    }

    static SinglyLinkedListNode reverse(SinglyLinkedListNode head) {

        if(head.next == null) return head;
        SinglyLinkedListNode preNode = head;
        SinglyLinkedListNode headNode = head.next;
        SinglyLinkedListNode postNode= headNode.next;

        while (postNode != null) {
            headNode.next = preNode;
            preNode = headNode;
            headNode = postNode;
            postNode = headNode.next;
        }
        head.next = null;
        headNode.next = preNode;



        return headNode;
    }
}

'Programming > Data Structure' 카테고리의 다른 글

[Hackerrank] SortedInsert  (0) 2020.12.02
[Hackerrank] ReversePrint  (0) 2020.12.02
[Hackerrank] ReverseADoublyLinkedList  (0) 2020.12.02
[Hackerrank] PrintLinkedList  (0) 2020.12.02
[Hackerrank] MergeTwoSortedLinkedLists  (0) 2020.12.02