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

Commit9d4674d

Browse files
authored
Java solution added for Linked List problems
Java solution added for below problems1) 19-Remove-Nth-node-from-end-of-List2) 2-Add-Two-Numbers
1 parent01a2b36 commit9d4674d

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
Name - Remove Nth Node From End of List
3+
Link - https://leetcode.com/problems/remove-nth-node-from-end-of-list/
4+
Condition - Could you do this in one pass?
5+
Time Complexity - O(n)
6+
Space Complexity - o(1)
7+
Note - Fast and slow pointer technique
8+
*/
9+
10+
classSolution {
11+
publicListNoderemoveNthFromEnd(ListNodehead,intk) {
12+
ListNodestart =newListNode(0);
13+
14+
ListNodeslow =start;
15+
ListNodefast =start;
16+
slow.next =head;
17+
18+
//Move fast in front so that the gap between slow and fast becomes n
19+
for (inti =1;i <=k +1;i++) {
20+
fast =fast.next;
21+
}
22+
//Move fast to the end, maintaining the gap
23+
while (fast !=null) {
24+
slow =slow.next;
25+
fast =fast.next;
26+
}
27+
//Skip the desired node
28+
slow.next =slow.next.next;
29+
returnstart.next;
30+
}
31+
}

‎java/2-Add-Two-Numbers.java‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
Name - Add Two Numbers
3+
Link - https://leetcode.com/problems/add-two-numbers/
4+
Time Complexity - O(m + n)
5+
Space Complexity - o(1)
6+
Note - make use of modulo (get remainder) and division (get quotient)
7+
*/
8+
9+
classSolution {
10+
publicListNodeaddTwoNumbers(ListNodefirst,ListNodesecond) {
11+
intq =0;
12+
intr =0;
13+
intsum =0;
14+
ListNodehead =null;
15+
ListNodetemp =null;
16+
while (first !=null ||second !=null) {
17+
sum =q + (((first !=null) ?first.val :0) + ((second !=null) ?second.val :0));
18+
r =sum %10;
19+
q =sum /10;
20+
ListNodenewNode =newListNode(r);
21+
if (head ==null) {
22+
head =newNode;
23+
}else {
24+
temp =head;
25+
while(temp.next!=null){
26+
temp=temp.next;
27+
}
28+
temp.next =newNode;
29+
newNode.next =null;
30+
}
31+
if (first !=null) {
32+
first =first.next;
33+
}
34+
if (second !=null) {
35+
second =second.next;
36+
}
37+
}
38+
if(q>0){
39+
ListNodenewNode =newListNode(q);
40+
temp =head;
41+
while(temp.next!=null){
42+
temp=temp.next;
43+
}
44+
temp.next =newNode;
45+
newNode.next =null;
46+
}
47+
returnhead;
48+
}
49+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp