LeetCode206.反转链表

206.反转链表

反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

(1)递归

public ListNode reverseList(ListNode head) {
        if(head==null)
            return head;
        if(head.next==null)
         	return head;
        ListNode last=reverseList(head.next);
        head.next.next=head;
        head.next=null;
        return last;
    }

在这里插入图片描述

(2)迭代

public ListNode reverseList(ListNode head) {
        if(head==null)
            return head;
        ListNode b,c;
        c=head;
        head=null;
        while(c!=null)
        {
            b=c.next;//先在前面占个位置
            c.next=head;//回头看看
            head=c;//自已变成头
            c=b;//继续向前
        }
        return head;
    }

在这里插入图片描述

141.环形链表

这类题注意首尾

示例 1:
在这里插入图片描述
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。

 public boolean hasCycle(ListNode head) {
        if(head==null||head.next==null)
        return false;
        ListNode man=head;
        ListNode kuai=head;//初始
        while(kuai!=null&&kuai.next!=null)
        {
            man=man.next;
            kuai=kuai.next.next;
            if(man==kuai)
                return true; 
        }
        return false;
    }

19.删除链表的倒数第 N 个结点

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

输入:head = [1], n = 1
输出:[]
示例 3:

输入:head = [1,2], n = 1
输出:[1]

 public ListNode removeNthFromEnd(ListNode head, int n) {
        int a=0,c=0;
         ListNode aa = new ListNode(0, head);
        ListNode b=aa;
        while(head!=null){
        a++;
        head=head.next;
    }
    for (int i = 1; i < a - n + 1; ++i)
     {
            b = b.next;
     }
    b.next=b.next.next;//只要你记住头节点,那这个链表就还没有消失
    ListNode dummy=aa.next;
    return dummy;
    }   

若有错误,欢迎留言。

  • 12
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值