Back to Leetcode Go

203. Remove Linked List Elements

website/content/ChapterFour/0200~0299/0203.Remove-Linked-List-Elements.md

1.7.11.2 KB
Original Source

203. Remove Linked List Elements

题目

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

Example:


Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

题目大意

删除链表中所有指定值的结点。

解题思路

按照题意做即可。

代码

go

package leetcode

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func removeElements(head *ListNode, val int) *ListNode {
	if head == nil {
		return head
	}
	newHead := &ListNode{Val: 0, Next: head}
	pre := newHead
	cur := head
	for cur != nil {
		if cur.Val == val {
			pre.Next = cur.Next
		} else {
			pre = cur
		}
		cur = cur.Next
	}
	return newHead.Next
}


<div style="display: flex;justify-content: space-between;align-items: center;"> <p><a href="https://books.halfrost.com/leetcode/ChapterFour/0200~0299/0202.Happy-Number/">⬅️上一页</a></p> <p><a href="https://books.halfrost.com/leetcode/ChapterFour/0200~0299/0204.Count-Primes/">下一页➡️</a></p> </div>