Java-----链表练习题(中)

 本篇碎碎念: 无碎碎念

今日份励志文案: 很多人认为他们在思考,其实他们只是在整理自己的偏见

目录

一206. 反转链表 - 力扣(LeetCode)

二链表中倒数第k个结点_牛客题霸_牛客网 (nowcoder.com)

三 链表分割_牛客题霸_牛客网 (nowcoder.com)


206. 反转链表 - 力扣(LeetCode)

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。 

这道题可以用递归实现也可以用循环实现(我用的是while循环) ,反转前的头节点是反转后的尾节点

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null){
            return head;
        }

        if(head.next==null){
            return head;
        }

        ListNode reversal=null;
        ListNode cur=head;

        while(cur!=null){

            ListNode middle=cur.next;
            cur.next=reversal;
            reversal=cur;
            cur=middle;

        }
        return reversal;
    }
}

 

链表中倒数第k个结点_牛客题霸_牛客网 (nowcoder.com)

输入一个链表,输出该链表中倒数第k个结点。

求出总共有几个元素,如何相减求出的值

判断这个值什么时候为0,为0就返回这个值也就是倒数第k个节点 

public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        if(k<=0||k>size(head)){
            return null;
        }else{
            k=size(head)-k;
        }
        ListNode cur=head;
        ListNode middle=head;
        
        while(k>0){
            cur=cur.next;
            k--;
        }
        
        return cur;
    }
    public int size(ListNode head){
        int count=0;
        while(head!=null){
            count++;
            head=head.next;
        }
        return count;
    }
}

三 链表分割_牛客题霸_牛客网 (nowcoder.com)

现有一链表的头指针 ListNode* pHead,给一定值x,编写一段代码将所有小于x的结点排在其余结点之前,且不能改变原来的数据顺序,返回重新排列后的链表的头指针。

 

public class Partition {
    public ListNode partition(ListNode pHead, int x) {
        // write code here

        if(pHead == null) {
            return null;
        }
        ListNode head = new ListNode(0);//虚拟头节点,方便一点
        ListNode resHead = head;//返回节点
        head.next = pHead;
        ListNode cur = head;
        ListNode pre = cur.next;

        while(pre != null) {
            if(pre.val < x){
                if(cur == head){
                    pre = pre.next;
                    cur = cur.next;
                    head = cur;
                }else{
                    ListNode tmp = pre;                
                    cur.next = tmp.next;
                    tmp.next = head.next;
                    head.next = tmp;
                    head = tmp;
                    pre = cur.next;
                }
            }else{
                cur = cur.next;
                pre = pre.next; 
            }

        }
        return resHead.next;
    }
}

  • 6
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值