LeetCode 203. Remove Linked List Elements 解题报告

203. Remove Linked List Elements

My Submissions
Question
Total Accepted: 52116  Total Submissions: 187218  Difficulty: 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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
Have you met this question in a real interview? 
Yes
 
No

Discuss


    要求删除链表中指定值的元素。考虑一个边界条件,val和head节点相同。构建一个仅作为标志作用的头指针,这个指针指向实际的head指针。

    我的AC代码

public class RemoveLinkedListElements {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ListNode h = new ListNode(1);
		ListNode h1 = new ListNode(1);
		h.next = h1;
		System.out.print(removeElements(h, 1));
	}

	public static ListNode removeElements(ListNode head, int val) {
		if (head == null) {
			return null;
		}

		ListNode h = new ListNode(0);
		h.next = head; // 仅作为标志作用的头指针
		ListNode pre = h;

		while (head != null) {
			if (head.val == val) {
				pre.next = head.next;
			} else {
				pre = pre.next;
			}
			head = head.next;

		}
		return h.next;
	}
}


你可能感兴趣的:(LeetCodeOJ)