链表的练习

1 删除链表中等于给定值 val 的所有节点.
先处理非头部节点, 最后处理头部节点.

class ListNode {
   
    int val = 0;
    ListNode next = null;
    
    public ListNode(int val) {
   
        this.val = val;
    }
}
public class LinkedListTest {
   
	public ListNode removeElements(ListNode head, int val) {
   
        if (head == null) {
   
            return null;
        }

1. 先删除中间节点的情况(非头部的情况)
        ListNode prev = head;  // prev 始终指向 cur 的前一个位置
        ListNode cur = head.next;
        while (cur != null) {
   
            if (cur.val == val) {
               
                prev.next = cur.next; 
                cur = prev.next;     
            } else {
                
                prev = cur;
                cur = cur.next;
            }
        }
2. 最后再考虑删除头结点的情况(放到最后, 只需要处理一次即可)
        if (head.val == val) {
   
            head = head.next;
        }
        return head;
    }
}

2 反转一个单链表.
定义三个节点, pre, next, 新的头结点. 最后返回的是 新的头结点.

 public ListNode reverseList(ListNode head) {
   
        if (head == null) {
   
            return null;
        }
        if (head.next == null) {
   
            return head;
        }
        ListNode newHead = null;
        ListNode cur = head;
        ListNode prev = null;
        while (cur!=null){
   
            ListNode next=cur.next;
            if(next==null){
   
                newHead=cur;
            }
            cur.next=prev;
            prev=cur;
            cur=next;
        }
        return newHead;
    }

3 给定一个带有头结点 head 的非空单链表,返回链表的中间结点. 如果有两个中间结点,则返回第二个中间结点.
先求链表长度, 然后求要走的步数. 是 <steps, 不是 <=steps.

public ListNode middleNode(ListNode head) {
   
        int steps = size(head) / 2;
        ListNode cur = head
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值