File tree Expand file tree Collapse file tree 2 files changed +123
-0
lines changed
Expand file tree Collapse file tree 2 files changed +123
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ Get Node Value
3+
4+ You’re given the pointer to the head node of a linked list and a specific position.
5+ Counting backwards from the tail node of the linked list, get the value of the node at the given position.
6+ A position of 0 corresponds to the tail, 1 corresponds to the node before the tail and so on.
7+
8+ Get Nth element from the end in a linked list of integers
9+ Number of elements in the list will always be greater than N.
10+ Node is defined as
11+
12+ class Node {
13+ int data;
14+ Node next;
15+ }
16+
17+ */
18+
19+ int GetNode (Node head ,int n ) {
20+ // This is a "method-only" submission.
21+ // You only need to complete this method.
22+
23+ Node prev =head ,ahead =head ;
24+
25+ for (int i =1 ;i <=n ;i ++)
26+ ahead =ahead .next ;
27+
28+ while (ahead .next !=null )
29+ {
30+ prev =prev .next ;
31+ ahead =ahead .next ;
32+ }
33+
34+ return prev .data ;
35+
36+ }
Original file line number Diff line number Diff line change 1+ /*
2+ Merge two sorted linked lists
3+
4+ You’re given the pointer to the head nodes of two sorted linked lists.
5+ The data in both lists will be sorted in ascending order.
6+ Change the next pointers to obtain a single, merged linked list which also has data in ascending order.
7+ Either head pointer given may be null meaning that the corresponding list is empty.
8+
9+ Merge two linked lists
10+ head pointer input could be NULL as well for empty list
11+ Node is defined as
12+ class Node {
13+ int data;
14+ Node next;
15+ }
16+ */
17+
18+ Node mergeLists (Node headA , Node headB ) {
19+ // This is a "method-only" submission.
20+ // You only need to complete this method
21+ Node head = null ;
22+ Node temp = null ;
23+
24+
25+ if (headA ==null )
26+ return headB ;
27+ if (headB ==null )
28+ return headA ;
29+
30+ while (headA !=null && headB !=null )
31+ {
32+ if (headA .data <headB .data )
33+ {
34+ if (head ==null )
35+ {
36+ head =headA ;
37+ headA =headA .next ;
38+ head .next =null ;
39+ temp =head ;
40+ }
41+ else
42+ {
43+ temp .next =headA ;
44+ headA =headA .next ;
45+ temp =temp .next ;
46+ temp .next =null ;
47+ }
48+ }
49+
50+ else
51+ {
52+ if (head ==null )
53+ {
54+ head =headB ;
55+ headB =headB .next ;
56+ head .next =null ;
57+ temp =head ;
58+ }
59+ else
60+ {
61+ temp .next =headB ;
62+ headB =headB .next ;
63+ temp =temp .next ;
64+ temp .next =null ;
65+ }
66+ }
67+ }
68+
69+ while (headA !=null )
70+ {
71+ temp .next =headA ;
72+ headA =headA .next ;
73+ temp =temp .next ;
74+ temp .next =null ;
75+ }
76+
77+ while (headB !=null )
78+ {
79+ temp .next =headB ;
80+ headB =headB .next ;
81+ temp =temp .next ;
82+ temp .next =null ;
83+ }
84+
85+ return head ;
86+
87+ }
You can’t perform that action at this time.
0 commit comments