Delete the list of all nodes to val

  1. Create a list of all the node value is not tail-val interpolating operation
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode result = null;
        ListNode cur = head;
		ListNode last=null;//用来记录当前链表的最后一个结点
        while (cur != null) {
            if (cur.val == val) {
                cur=cur.next;
                continue;//结束本次循环
            }
            else
            {
				ListNode next=cur.next;
				cur.next=null;
				if(result==null){//进行尾插时考虑链表是否为空
					result=cur;
				}
				else{
					last=last.next;//查找最后一个结点
				}
				last=cur;
				cur=next;
			}
		}
			return result;
	}
}

2. Set the two references, and the first node a special treatment

class Solution {
    public ListNode removeElements(ListNode head, int val) {
         ListNode prev = null;//始终指向cur的前驱结点
        ListNode cur = head;
        
        while (cur != null) 
	{
            if (cur.val == val) {
                if (cur == head) {
                    head = cur.next;
		    cur = cur.next;//对头结点进行处理,防止要删除的结点出现在第一个位置
                } else {
                    prev.next = cur.next;//若不对头结点进行处理,prev会报错
		    cur = cur.next;
		}
            } 
	    else {
	      prev = cur;
	      cur = cur.next;
           }
        }
        
        return head;
    }
}

3. Set two references, the last skip the first processing node

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

        
        return head;
    }
}//对头结点进行最后处理

4. Set the two references, and forcibly add a predecessor node

class Solution {
	public ListNode removeElements(ListNode head, int val) {

        ListNode tmpHead = new ListNode(-1);//强行加一个前驱结点

        tmpHead.next = head;

        ListNode prev = tmpHead;

        ListNode cur = head;

        while (cur != null) {

            if (cur.val == val) {

                prev.next = cur.next;

            } else {

                prev = cur;

            }
			cur = cur.next;
		}
	return tmpHead.next;
	}
}

 

Published 40 original articles · won praise 4 · Views 888

Guess you like

Origin blog.csdn.net/weixin_44919969/article/details/97484591