首页 > 代码库 > LeetCode -- 删除链表中值为k的元素

LeetCode -- 删除链表中值为k的元素

本题目比較直接,一次遍历遇到匹配的元素直接删除(通过n.next = n.next.next)就能够了,仅仅是须要考虑到:
1.首节点的情况
2.末节点的情况


下面为实现:

public ListNode RemoveElements(ListNode head, int val) {
    
    // null list
	if(head == null){
		return null;
	}
	// constains only one node
	if(head.next == null && head.val == val){
		return null;
	}
	
	//remove first nodes
	while(head.val == val){
	    if(head.next == null){
	        break;
	    }
		head = head.next;
	}
	var tmp = head;
	
	// nodes in between
	while(head.next != null){
		if(head.next.val == val){
			head.next = head.next.next;
		}
		else{
			head = head.next;
		}
		if(head.next == null){
			break;
		}
	}
	// last node
	if(head.val == val){
		return null;
	}
	
	// restore head node
	head = tmp;
	
	return head;
	
    }


LeetCode -- 删除链表中值为k的元素