@@ -78,15 +78,65 @@ static ListNode appendNode(ListNode head, ListNode nodeToInsert) {
78
78
return head ;
79
79
}
80
80
81
+ static ListNode reverseList (ListNode head ) {
82
+ ListNode curr = head ;
83
+ ListNode prev = null ;
84
+ while (curr != null ) {
85
+ ListNode nextTemp = curr .next ;
86
+ curr .next = prev ;
87
+ prev = curr ;
88
+ curr = nextTemp ;
89
+ }
90
+ return prev ;
91
+ }
92
+
93
+ static ListNode addTwoNumbers (ListNode l1 , ListNode l2 ) {
94
+ ListNode l3 = new ListNode ();
95
+ ListNode temp = l3 ;
96
+ int sum ;
97
+ int carry = 0 ;
98
+ while (l1 != null || l2 != null ) {
99
+ sum = 0 ;
100
+
101
+ if (l1 == null ) {
102
+ sum += l2 .val + carry ;
103
+ l2 = l2 .next ;
104
+ }
105
+ else if (l2 == null ) {
106
+ sum += l1 .val + carry ;
107
+ l1 = l1 .next ;
108
+ }
109
+ else {
110
+ sum += l1 .val + l2 .val + carry ;
111
+ l1 = l1 .next ;
112
+ l2 = l2 .next ;
113
+ }
114
+ carry = sum / 10 ;
115
+ sum = sum % 10 ;
116
+ temp .val = sum ;
117
+
118
+ if (l1 != null || l2 != null ) {
119
+ temp .next = new ListNode ();
120
+ temp = temp .next ;
121
+ }
122
+ else if (carry > 0 ) {
123
+ temp .next = new ListNode (carry );
124
+ }
125
+ }
126
+ return l3 ;
127
+ }
128
+
81
129
public static void main (String [] args ) {
82
- ListNode node1 = new ListNode (1 );
83
- node1 .next = new ListNode (2 );
84
- node1 .next .next = new ListNode (4 );
130
+ ListNode node1 = new ListNode (2 );
131
+ node1 .next = new ListNode (4 );
132
+ node1 .next .next = new ListNode (3 );
85
133
86
- ListNode node2 = new ListNode (1 );
87
- node2 .next = new ListNode (3 );
134
+ ListNode node2 = new ListNode (5 );
135
+ node2 .next = new ListNode (6 );
88
136
node2 .next .next = new ListNode (4 );
89
137
90
- ListNode mergedList = mergeTwoLists (node1 , node2 );
138
+ // ListNode mergedList = mergeTwoLists(node1, node2);
139
+ // reverseList(node1);
140
+ // addTwoNumbers(node1, node2);
91
141
}
92
142
}
0 commit comments