Java 反转链表

题目:

给定一个单链表的头结点pHead,长度为n,反转该链表后,返回新链表的表头。

数据范围: n\leq1000n≤1000

要求:空间复杂度 O(1)O(1) ,时间复杂度 O(n)O(n) 。

如当输入链表{1,2,3}时,

经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。

原题链接:反转链表_牛客题霸_牛客网

对于这题,我做了3种解法(第三种看了别人的):

(1)传统指针法:

public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head == null){
            return null;
        }
        ListNode p = head;
        ListNode q = head.next;
        p.next = null;
        ListNode swap = null;
        while(q != null){
            //换
            swap = q.next;
            q.next = p;
            //移
            p = q;
            q = swap;
        }
        return p;
    }
}

(2) 使用栈

要import java.util.Stack;

public ListNode ReverseList(ListNode head) {

        if(head == null){
            return null;
        }
        Stack<ListNode> stack = new Stack<>();
        ListNode current = head;
        ListNode tail = head;
        //入栈
        while(current != null){
            tail = current.next;
            stack.push(current);
            current = tail;
        }
        //记录新的head
        tail = stack.peek();
        //重连指针
        while(!stack.empty()){
            current = stack.pop();
            if(stack.empty()){
                current.next = null;
                break;
            }
            current.next = stack.peek();
        }
        return tail;

}

(3) 递归

  public ListNode ReverseList(ListNode head) {
        //递归
       //当链表为空时,或者到最后一个结点时返回
        if(head==null||head.next==null){
            return head;
        }
        //这里最后一个结点返回为头结点
        ListNode temp=ReverseList(head.next);
        head.next.next=head;
        //这里目的是把原来的头节点的next变为null
        head.next=null;
        //返回头结点
       return temp;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值