码迷,mamicode.com
首页 > 其他好文 > 详细

删除链表中的元素

时间:2020-09-16 12:24:18      阅读:32      评论:0      收藏:0      [点我收藏+]

标签:link   code   class   防止   lse   删除   https   amp   nod   

/**
* 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;
}
}

删除链表中的元素

标签:link   code   class   防止   lse   删除   https   amp   nod   

原文地址:https://www.cnblogs.com/xiaowenwen/p/13604539.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!