备战秋招--day1

  1. 移除链表元素

https://leetcode.cn/problems/remove-linked-list-elements/submissions/

两种想法:

  1. 加头节点dummy、

设置虚拟头节点,可以按照统一的方式进行移除


class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if(head == null){
            return head;
        }

        ListNode dummy = new ListNode(-1,head);
        ListNode pre = dummy;
        ListNode cur = head;

        while(cur != null){
            if(cur.val == val){
                pre.next = cur.next;
            }else{
                pre =cur;
            }
            cur =cur.next;
        }
return dummy.next;
    }
}
  1. 不加虚拟节点

class Solution {
    public ListNode removeElements(ListNode head, int val) {
        while(head !=null && head.val == val){
            head = head.next;
        }
        if(head == null){
            return head;
        }

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

2.24两两交换链表的节点

https://leetcode.cn/problems/swap-nodes-in-pairs/submissions/

加一个头节点,一个临时节点

class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummynode = new ListNode(-1);//虚拟节点
        dummynode.next = head;
        ListNode cur = dummynode;
        ListNode firstnode;
        ListNode secondnode;
        ListNode temp;

        while(cur.next != null && cur.next.next != null){
            temp = cur.next.next.next;
            firstnode=cur.next;
            secondnode = cur.next.next;
            //两两交换
            cur.next = secondnode;
            secondnode.next = firstnode;
            firstnode.next = temp;
            //准备新一轮,cur
            cur=firstnode;
        }
        return dummynode.next;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_56194193/article/details/129326883