移除鏈表元素
題目描述:給你一個鏈表的頭節(jié)點 head 和一個整數(shù) val ,請你刪除鏈表中所有滿足 Node.val == val 的節(jié)點,并返回 新的頭節(jié)點 。
示例說明請見LeetCode官網(wǎng)。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/remove-linked-list-elements/
著作權歸領扣網(wǎng)絡所有。商業(yè)轉(zhuǎn)載請聯(lián)系官方授權,非商業(yè)轉(zhuǎn)載請注明出處。
解法一:鏈表遍歷
首先,初始化一個結(jié)點firstNode指向head結(jié)點,cur指向head結(jié)點,last指向firstNode結(jié)點,然后開始遍歷:
- 首先cur不能為空;
- 如果cur結(jié)點的值等于目標值val,則將last的next指向cur的next,并且cur賦值為cur的next;
- 如果cur結(jié)點的值不等于目標值val,則將last和cur結(jié)點往后移一位。
遍歷結(jié)束后,返回firstNode的next結(jié)點即為處理后的鏈表。
public class LeetCode_203 {
public static ListNode removeElements(ListNode head, int val) {
ListNode firstNode = new ListNode(-1);
firstNode.next = head;
ListNode cur = firstNode.next;
ListNode last = firstNode;
while (cur != null) {
if (cur.val == val) {
last.next = cur.next;
cur = last.next;
} else {
last = cur;
cur = cur.next;
}
}
return firstNode.next;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(6);
head.next.next.next = new ListNode(3);
head.next.next.next.next = new ListNode(6);
removeElements(head, 6);
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
}
}
【每日寄語】 在這個并非盡善盡美的世界上,勤奮會得到報償,而游手好閑則要受到懲罰。