Skip to content

Commit 302b829

Browse files
authored
Update Append Last N to First
1 parent 10d8382 commit 302b829

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

Course 2 - Data Structures in JAVA/Lecture 7 - Linked Lists I/Append Last N to First

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,62 @@ We have been required to move the last 4 nodes to the front of the list. Here, "
4141
When we move this list to the front then the remaining part of the initial list which is, "10->6->77" is attached after 100.
4242
Hence, the new list formed with an updated head pointing to 90.
4343
*/
44+
/*
45+
46+
Following is the Node class already written for the Linked List
47+
48+
class LinkedListNode<T> {
49+
T data;
50+
LinkedListNode<T> next;
51+
52+
public LinkedListNode(T data) {
53+
this.data = data;
54+
}
55+
}
56+
57+
*/
58+
59+
public class Solution {
60+
61+
public static LinkedListNode<Integer> appendLastNToFirst(LinkedListNode<Integer> head, int n) {
62+
//Your code goes here
63+
LinkedListNode<Integer> node=head,checkNode=null,newHead=null;
64+
if (n==0)
65+
{
66+
return head;
67+
}
68+
69+
int count=0;
70+
while(node!=null)
71+
{
72+
node=node.next;
73+
count=count+1;
74+
}
75+
if (count<n)
76+
{
77+
return head;
78+
}
79+
80+
n=count-n;
81+
node=head;
82+
for (int i=0;i<n-1;i++)
83+
{
84+
node=node.next;
85+
}
86+
checkNode=node.next;
87+
node.next=null;
88+
newHead=checkNode;
89+
//System.out.println("Shifting from element: "+checkNode.data);
90+
//System.out.println("Now last element is: "+node.data);
91+
//System.out.println("Now first element is: "+newHead.data);
92+
while(checkNode.next!=null)
93+
{
94+
checkNode=checkNode.next;
95+
}
96+
checkNode.next=head;
97+
head=newHead;
98+
return head;
99+
100+
}
101+
102+
}

0 commit comments

Comments
 (0)