【LeetCode刷题笔记】206. 反转链表:给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

206. 反转链表

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。https://leetcode.cn/problems/reverse-linked-list/

示例 :
在这里插入图片描述

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

方法一:双指针迭代
在这里插入图片描述
代码示例:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode pre =null;
        ListNode cur =head;
        while(cur != null){
        ListNode temp =cur.next;
        cur.next =pre;
        pre=cur;
        cur =temp;
        }
        return pre;
    }
}

思路分析:
在这里插入图片描述
方法二:用栈实现

 public ListNode reverseList(ListNode head) {
        Stack<ListNode> stack  =new Stack<>();
        ListNode start =new ListNode(0,new ListNode(0));
        ListNode temp =start;
        while(head !=null){
            stack.push(head);
            head = head.next;   
    } 
        while(!stack.isEmpty()){
            temp.next =stack.pop();
            temp =temp.next;
    }
    temp.next =null;
    return start.next;
}

思路分析:
在这里插入图片描述

方法三:头插法

  public ListNode reverseList(ListNode head) {
        ListNode node =null;
        for(ListNode x=head;x !=null;x=x.next){
            node =new ListNode(x.val,node);
        }  return node;
    }  

思路分析:在这里插入图片描述
附:

  • 方法二建议使用Deque代替stack(官方推荐Dequehttps://blog.csdn.net/Tommy_____/article/details/106445631

  • Deque
    允许两头都进,两头都出,这种队列叫双端队列(Double Ended Queue),简称Deque。
    Java集合提供了接口Deque来实现一个双端队列,它的功能:
    ①既可以添加到队尾,也可以添加到队首;
    ②既可以从队首获取,又可以从队尾获取。
    在这里插入图片描述

  • Stack的入栈和出栈的操作:
    ①把元素压栈:push(E);
    ②把栈顶的元素“弹出”:pop(E);
    ③取栈顶元素但不弹出:peek(E)。

  • 在Java中,我们用Deque可以实现Stack的功能:
    ①把元素压栈:push(E)/addFirst(E);
    ②把栈顶的元素“弹出”:pop(E)/removeFirst();
    ③取栈顶元素但不弹出:peek(E)/peekFirst()。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值