删除链表中的元素

/**
* https://leetcode-cn.com/problems/remove-linked-list-elements/
* 删除链表中等于给定值 val 的所有节点。
*
* 输入: 1->2->6->3->4->5->6, val = 6
* 输出: 1->2->3->4->5
*/
public class RemoveListElements203 {

public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}

/**
* 带虚拟头节点的链表
* @param head
* @param val
* @return
*/
public ListNode removeElements(ListNode head, int val) {
if(head == null) return head;
ListNode dummyHead = new ListNode( -1);
dummyHead.next = head;
ListNode pre = dummyHead;
while(pre.next != null){
if(pre.next.val == val){
ListNode tempNode = pre.next;
pre.next = tempNode.next;
}else
pre = pre.next; //为了防止紧接着下一个也是要删除的对象
}
return dummyHead.next;
}

/**
* 不带虚拟头节点的链表
* @param head
* @param val
* @return
*/
public ListNode removeElements2(ListNode head, int val) {
while (head != null && head.val == val){
head = head.next;
}

if(head == null)
return null;

ListNode cur = head;
while(cur.next != null){
if(cur.next.val == val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
return head;
}
}
posted @ 2020-09-02 21:32  文所未闻  阅读(280)  评论(0编辑  收藏  举报