Remove Linked List Elements (0203/Easy)

Remove all elements from a linked list of integers that have value val.

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5

思路:这道题就是遍历链表的每个元素,如果相等,删除,问题是如何让被删除节点的上一个的next指向下一个节点,所以,我们需要重新建立一个指向head的新节点,这样就可以完成该内容了。有两种解决办法

(1)定义两个指针,pre.next=head,cur=head,pre和cur同时向后移动。

(2)定义一个指针,一直用这个指针的next进行访问。

public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode correct=new ListNode(0);//定义一个新节点,next指向head
         correct.next=head;  
        ListNode cur=correct;
        while(cur.next!=null)//从head开始判断
        {
            if(cur.next.val==val)//如果相等,则删除
            {
                cur.next=cur.next.next; //保证被删除节点的前一个节点的next指向下一个节点                        
            }
            else
            {
                cur=cur.next;   //指针移动         
            }
        }
        return correct.next;//返回的时候从head开始返回
    }
}

results matching ""

    No results matching ""