Linked list OJ question (JavaDS)

Leetcode 203. Remove linked list elements

To delete an element, be sure to find the previous node with the deleted element and modify the point to

public void removeAll(int key){
    
    
//首先判空
        if(this.head==null){
    
    
            return;
        }
        ListNode prev=this.head;
        ListNode cur=this.head.next;
        //从第二个结点开始判断
        while(cur!=null){
    
    
            if(cur.val==key){
    
    
                prev.next=cur.next;
            }
            else{
    
    
                prev=cur;
            }
            cur=cur.next;
        }
        //最后判断第一个节点,如果放在前面判断,那么头节点如果是要删除的则没有删
        if(this.head.val==key){
    
    
            this.head=this.head.next;
        }
    }

Palindrome structure of Niuke OR36 linked list

insert image description here

First find the middle node of the linked list, reverse the linked list on the right, compare the reversed part and the first half one by one, if each node is equal, it is a palindrome structure

insert image description here

Note that the tail of the reversed part is not empty, and it does not point to null at the end. If you make a mistake and judge an odd number of nodes, a null pointer exception will occur

If there are an odd number of nodes, the condition for the end of the loop is that the left and right pointers point to the same element. If there are an even number of nodes, the condition for the end of the loop is that the left pointer's next==right pointer

public boolean chkPalindrome(ListNode A) {
    
    
        if(A==null){
    
    
        //空表不是回文结构
            return false;
        }
        if(A.next==null){
    
    
            return true;
        }
        //快慢指针找中间节点
        ListNode fast=A;
        ListNode slow=A;
        while(fast!=null&&fast.next!=null){
    
    
            slow=slow.next;
            fast=fast.next.next;
        }
        //反转后半部分链表
        ListNode cur=slow.next;
        while(cur!=null){
    
    
            ListNode next=cur.next;
            cur.next=slow;
            slow=cur;
            cur=next;
        }
        
        while(A!=slow){
    
    
            if(A.val!=slow.val){
    
    
                return false;
            }
            if(A.next==slow){
    
    
            //如果是偶数个结点
                return true;
            }
            A=A.next;
            slow=slow.next;
        }
        return true;
    }

Guess you like

Origin blog.csdn.net/qq_63983125/article/details/127155824