Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitc44cb4d

Browse files
remove linked list elements
1 parent640056f commitc44cb4d

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
packageeasy;
2+
3+
importclasses.ListNode;
4+
importutils.CommonUtils;
5+
6+
/**203. Remove Linked List Elements QuestionEditorial Solution My Submissions
7+
Total Accepted: 74027
8+
Total Submissions: 249238
9+
Difficulty: Easy
10+
Remove all elements from a linked list of integers that have value val.
11+
12+
Example
13+
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
14+
Return: 1 --> 2 --> 3 --> 4 --> 5*/
15+
publicclassRemoveLinkedListElements {
16+
/**This is a very good question to test your understanding of pointers/memory/addresses, although it's marked as EASY.
17+
* All the three nodes: dummy, curr and prev are indispensable.
18+
19+
* 1. Eventually, we should return dummy.next as the final result.
20+
* 2. we assign head to curr, dummy to prev
21+
* 3. and then we use prev and curr to traverse through the list and do the work
22+
* 4. each time, we only move one node forward, so we don't need another while loop inside the while loop*/
23+
publicListNoderemoveElements(ListNodehead,intval) {
24+
ListNodedummy =newListNode(-1);
25+
dummy.next =head;
26+
ListNodecurr =head,prev =dummy;
27+
while(curr !=null){
28+
if(curr.val ==val){
29+
prev.next =curr.next;
30+
}else {
31+
prev =prev.next;
32+
}
33+
curr =curr.next;
34+
}
35+
returndummy.next;
36+
}
37+
38+
publicstaticvoidmain(String...strings){
39+
RemoveLinkedListElementstest =newRemoveLinkedListElements();
40+
intval =1;
41+
ListNodehead =newListNode(1);
42+
ListNoderes =test.removeElements(head,val);
43+
CommonUtils.printList(res);
44+
}
45+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp