【剑指Offer】面试题24:反转链表

/**
 * 面试题24:反转链表.leetcode HOT100第206题
 * 输入一个链表,反转链表后,输出新链表的表头。
 * 输入{1,2,3},输出{3,2,1}
 * @author dengjie
 * @create 2021-03-23 12:32
 */
public class Solution24 {
    public static void main(String[] args) {
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        Node node5 = new Node(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        Node res = reverseListThree(node1);
        System.out.println(res);
    }

    /**
     * 方法一:迭代,剑指Offer,头插法
     * @param head
     * @return
     */
    public static Node reverseList(Node head){
        if (head == null || head.next == null){
            return head;
        }
        Node newHead = new Node(0);//链表反转后的头节点
        Node temp = null;//记录当前节点的下一个节点
        Node pHead = head;//指向当前节点
        while (pHead != null){
            temp = pHead.next;
            pHead.next = newHead.next;
            newHead.next = pHead;
            pHead = temp;
        }
        return newHead.next;
    }


    /**
     * leetcode206简单题,迭代
     * @return
     */
    public static Node reverseListTwo(Node head){
        if(head == null || head.next == null){
            return head;
        }
        Node pre = null;
        Node cur = head;
        while (cur != null){
            Node temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }

    /**
     * 方法三:递归
     * @param head
     * @return
     */
    public static Node reverseListThree(Node head){
        if (head == null || head.next == null) {
            return head;
        }
        // 想象递归已经层层返回,到了最后一步
        // 以链表 1->2->3->4->5 为例,现在链表变成了 5->4->3->2->null,1->2->null(是一个链表,不是两个链表)
        // 此时 newHead是5,head是1
        Node newHead = reverseList(head.next);
        // 最后的操作是把链表 1->2->null 变成 2->1->null
        // head是1,head.next是2,head.next.next = head 就是2指向1,此时链表为 2->1->2
        head.next.next = head;
        // 防止链表循环,1指向null,此时链表为 2->1->null,整个链表为 5->4->3->2->1->null
        head.next = null;
        return newHead;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值