剑指offer16 反转链表

注意:

输入参数:链表头指针为null或者链表中只有一个节点的用例。

测试用例:

  • null
  • 只有一个节点
  • 多个节点
import BrushProblem.swordOffer2.ListNode;

import java.util.Stack;

/**
 * @Auther: 
 * @Date: 2018/11/6 18:38
 * @Description: 反转链表
 */
public class ReverseList {

    public static void main(String[] args) {
        ListNode listNode=new ListNode(1);
        ListNode listNode2=new ListNode(2);
        ListNode listNode3=new ListNode(3);
        listNode.next=listNode2;
        listNode2.next=listNode3;

        ReverseList obj=new ReverseList();
        ListNode res=obj.ReverseList3(listNode);
    }

    /*
    * 剑指offer思路 112页
    * 定义3个节点
    * 分别指向:当前节点,当前节点的前一个节点,当前节点的后一个节点
    *
    * */
    public ListNode ReverseList(ListNode head) {
          if(head==null||head.next==null)
            return head;

        ListNode pre=null;
        ListNode cur=head;
        ListNode next=cur.next;
        while (cur!=null){
            next=cur.next;
            cur.next=pre;
            pre=cur;
            cur=next;
        }
        return pre;
    }

    public ListNode ReverseList2(ListNode head) {
        //这里最好前面写上<ListNode>,new后面可以不写,不然后面pop出来的数据是object类型的
        Stack<ListNode> stack=new Stack<>();
        while (head!=null){
            stack.push(head);
            head=head.next;
        }
        if(stack.isEmpty()){
            return null;
        }
        ListNode newHead=stack.pop();
        ListNode cur=newHead;
        while (!stack.isEmpty()){
            cur.next=stack.pop();
            cur=cur.next;
        }
        //这里一定要设置cur.next=null,因为不设置的话,cur.next不是空的。
        //例如输入用例为:4->5
        // head=cur=5
        // cur.next=4,cur=cur.next,即cur=4,这时cur的next是5,5的next是4,就成了死循环
        cur.next=null;
        return newHead;
    }

    //因为方法2基于栈,而递归的本质就是一个栈结构,所以也可以用递归结决问题
    ListNode result=new ListNode(0);
    ListNode cur=result;
    public ListNode ReverseList3(ListNode head) {
        if(head==null||head.next==null){
            return head;
        }
        recursive(head);
        cur.next=null;
        return result.next;
    }

    private void recursive(ListNode node){
        if(node.next!=null){
            recursive(node.next);
        }
        cur.next=node;
        cur=cur.next;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值