实现单链表的反转(LeetCode206)

实现单链表的反转--LeetCode206

  • 题目
  • 几种实现方式
  • 具体实现

题目

Reverse a singly linked list.
Example:
Input:1->2->3->4->5->NULL
Output:5->4->3->2->1->NULL

几种实现方式

就地反转法
新建链表,头节点插入法
递归反转法

具体实现

不啰嗦,直接看代码
(单链表实现看之前文章https://blog.csdn.net/u014229347/article/details/88966409)

/**
 * 实现单链表的反转(LeetCode206)
 *
 * @author llspace
 * @since  2019-04-12
 */
public class SingleLinkedListReverse {

    public static void main(String[] args) {
        SingleLinkedList singleLinkedList = new SingleLinkedList<>();
        singleLinkedList.addHead(1);
        for(int i = 2; i < 6; i++){
            singleLinkedList.addNode(i, i-1);
        }
        singleLinkedList.print();

        //测试单链表反转
        //singleLinkedList = reverse(singleLinkedList);
        //singleLinkedList = reverse1(singleLinkedList);
        singleLinkedList = reverse2(singleLinkedList);
        singleLinkedList.print();
    }

    /**
     * 就地反转法
     *
     * @param input
     * @return
     */
    public static SingleLinkedList reverse(SingleLinkedList input){
        SingleLinkedList.Node head = input.getHead();
        SingleLinkedList.Node next = head.next;

        while(next != null){
            input.addHead(next.value);
            head.next = next.next;
            next = next.next;
        }
        return input;
    }

    /**
     * 新建链表,头节点插入法
     *
     * @param input
     * @return
     */
    public static SingleLinkedList reverse1(SingleLinkedList input){
        SingleLinkedList output = new SingleLinkedList<>();
        SingleLinkedList.Node head = input.getHead();

        while(head != null){
            output.addHead(head.value);
            head = head.next;
        }

        return output;
    }

    /**
     * 递归反转法
     *
     * @param input
     * @return
     */
    public static SingleLinkedList reverse2(SingleLinkedList input){
        input.setHead(reverseNode(input.getHead()));
        return input;
    }

    public static SingleLinkedList.Node reverseNode(SingleLinkedList.Node head){
        if(head == null || head.next == null) {
            return head;
        }
        SingleLinkedList.Node node = reverseNode(head.next);
        head.next.next = head;
        head.next = null;
        return node;
    }

}

你可能感兴趣的:(算法与数据结构)