-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDoubleANumberRepresentedAsALinkedList2816.java
61 lines (47 loc) · 1.54 KB
/
DoubleANumberRepresentedAsALinkedList2816.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import java.util.Stack;
public class DoubleANumberRepresentedAsALinkedList2816 {
/*
* You are given the head of a non-empty linked list representing a non-negative integer without leading zeroes.
* Return the head of the linked list after doubling it.
*/
//* Definition for singly-linked list.
public class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class Solution {
// using stack :- 21ms
public ListNode doubleIt(ListNode head) {
Stack<Integer> st = new Stack<>() ;
while (head != null) {
st.push(head.val) ;
head = head.next ;
}
int num = 0 ;
ListNode nList = null;
while (!st.isEmpty() || num != 0) {
nList = new ListNode(0 , nList) ;
if(!st.isEmpty()){
num += st.pop() *2;
}
nList.val = num % 10;
num /= 10;
}
return nList ;
}
// using pointer method : - 2ms
public ListNode OptimaldoubleIt(ListNode head) {
if (head.val > 4) head = new ListNode(0 , head) ;
for (ListNode node = head ; node != null ; node = node.next){
node.val = (node.val *2) % 10 ;
if (node.next != null && node.next.val > 4) {
node.val++;
}
}
return head;
}
}
}