I Wanna Concatenate 2 Singly Linked List with Ordered into one linked list.Each lists nude have a score value. And ı wanna order and concatenate 2 list.
SinglyLinkedList* conList = list1->concatLists(list2);
SinglyLinkedList* SinglyLinkedList::concatLists(SinglyLinkedList* list2)
{
}
You need to walk through your first list and get the very final node and set the next node to the second node.
SinglyLinkedList* n = list1;
while(n->next != null){
n = n->next;
}
n->next = list2
Related
I am trying to write a program which
outputs all possible cycles starting and ending with node 1 and visiting all other nodes exactly once.
Given is a complete undirected unweighted graph with N nodes.
For example:
n = 4 then
1-2-3-4, 1-2-4-3, 1-3-2-4, 1-3-4-2, 1-4-3-2, 1-4-2-3
My approach would be to use Hamilton-circle method to find out a possible combination and then iterate until all combinations are calculated.
I assume the complexity is (n-1)!
class Permutation
main {
string list1 = "1"
string list2 = "2,3,4"
l2 = list2.length()
init Permutation
permutaion.permute (list2, 0, n-1)!
print list1 + list2
}
permute(list2, start, end) {
if (start==end)
print list2
else
for (i=start, i<=end, i++)
list2 = swap(list2, start, i)
permute(list2, start+1, end)
list2 = swap(list2, start, i)
}
Thank you for your time and help!
So I have a binary search tree and need to produce a list with the BSTtoList method, but I'm not sure what the general steps are or what I have to do.
class BinarySearchTree[A](comparator: (A, A) => Boolean) {
var root: BinaryTreeNode[A] = null
def search(a: A): BinaryTreeNode[A] = {
searchHelper(a, this.root)
}
def searchHelper(a: A, node: BinaryTreeNode[A]): BinaryTreeNode[A] = {
if(node == null){
null
}else if(comparator(a, node.value)){
searchHelper(a, node.left)
}else if(comparator(node.value, a)){
searchHelper(a, node.right)
}else{
node
}
}
def BSTtoList: List[A] = {
var sortedList = List()
if (root.left != null) {
sortedList :+ searchHelper(root.value, root.left).value
}
else if (root.right != null){
sortedList :+ searchHelper(root.value, root.right).value
}
sortedList
}
}
Let's first think about how a BST works. At any given node, say with value x, all the nodes in the left subtree will have values < x and all nodes in the right subtree will have values > x. Thus, to return the sorted list of the subtree rooted at node x, you just have to return [sorted list of left subtree] + [x] + [sorted list of right subtree], so you just have to call BSTtoList recursively on the left and right subtrees, and then return the list described above. From there you just have to handle the base case of returning an empty list at a NULL node.
The above algorithm is O(N^2) time, and there's a better solution using tail recursion that runs in O(N) time, pseudocode for which:
def BSTtoList(root, accumulator):
if root == NULL:
return accumulator
else:
return BSTtoList(root.left_child, [root.value] + BSTtoList(root.right_child, accumulator)
Where BSTtoList is initially called with an empty list as the accumulator. This second solution works similarly to the first but is optimized by minimizing array merges (this version works best if the language used has O(1) insertion into the front of a list; implementation is a bit different if the language allows O(1) insertion into the back).
My reverse linked list function seems to be buggy, but even after looking online for solutions, I could not understand why my method fails in a dry run with three nodes :(
In other solutions the starred part is usually written as 'head.next.next = head'. Isn't my line with 'n.next = head' doing the same thing?
Also some other solution had a line before calling the method as:
Node secondElem = head.next;
head.next = NULL;
I didn't understand why this is needed either :(
I came up with this solution and can't seem to proceed from here:
Node reverseLL(Node head){
if (head == NULL || head.next == NULL) return head;
Node n = reverseLL(head.next);
n.next = head; //**
head.next = NULL
return n;
}
Can someone please explain this to me?
When you reverse a linked list recursively, you need to attach the former head to the very end. This is something where the result of the reversal of the rest of the list is not really helpful -- in fact you'll just want to return that in the end.
But there is one thing that is important to be aware of: The second element will become the last element of the reversed rest of the list. And head.next will still hold a reference to it after reversal of the rest.
Example
Original list
head = 1 -> 2 -> 3 -> NULL
The reversed sublist returned from the recursive call (head will still be 1 and head.next will still point to 2)
3 -> 2 -> NULL
You can use this to append the head to the end after the recursive call that reverses the rest:
Node reverseLL(Node head) {
if (head == NULL || head.next == NULL) return head;
Node n = reverseLL(head.next);
head.next.next = head;
head.next = NULL;
return n;
}
I have written below code to reverse the first K nodes of linked list, It had some issue resolved in Reversing first K nodes of Linked List,Why recursion executing twice for last iteration, Now it working expected but why it leads to loop in linked list when i try to use variable "k" instead of "presentCounter" in "if" condition,what is the reason? and how to avoid it?
/*
* Condition K <= Length of linked list.
* node = null
* nextNode headNode of the linked list
*/
public void reverseNode(Node node, Node nextNode, int k) {
int presentCounter = k;
if (k > 1) {
k = k - 1;
this.reverseNode(nextNode, nextNode.next, k);
}
if (presentCounter == 1) {
this.kNode = nextNode.next; // Saving K's Next Node
this.headNode = nextNode; // Setting K node as head node
}
if (node == null) {
nextNode.next = this.kNode;
} else
nextNode.next = node;
}
Because presentCounter is also used later to check for the last element to swap with if (presenceCount == 1).
If you naively get rid of k and use presentCounter instead
if (presentCounter > 1) {
presentCounter = presentCounter - 1;
this.reverseNode(nextNode, nextNode.next, presentCounter);
}
since now presentCounter has been decremented, the check for the last element to swap triggers one item before.
For example in the list [a b c d] when requested to swap the first three elements, the check should be true for c so that this.kNode is d.
If instead is true one step before, i.e. for b, then this.kNode is c (and the head is set to b).
When linking the elements in reverse order (c b a), the old head1 is linked to this.kNode, so we end up with two different result:
Corret (this.kNode is d)
c b a d
Incorrect (this.kNode is c)
b a c b a c ...
The second one is a loop.
You can easily get rid of k though
if (presentCounter > 1)
this.reverseNode(nextNode, nextNode.next, presentCounter-1);
In order to better understand what is going on, here is a picture.
You have to understand that there are two phases: the traversing phase
(when the recursion call is made) and the building phase (when the recursion
calls have returned).
So each invocation is pictured twice.
pc stands for presentCounter
1 the first element, the one saved in nextNode when node is null, ie the first invocation of the function.
When k is 2 it enters the first condition (k > 1)
then it will decrement k and recurse
but then after the recursion finishes it will continue to the next line.
k=k-1 gives 1, so "if (k == 1)" will perform the actions inside that second conditional as well on the same pass.
By saving k into presentCounter before you subtract one from it, then checking presentCounter == 1, you avoid this extra task being done twice (once inside the recursion call because k == 1 now, and again when the recursion finishes).
This is an interview question(again).
Given a singly connected linked list, find the largest palindrome
in the list. (You may assume the length of the palindrome is even)
The first approach I made was using a stack - we traverse over the list from the start and keep pushing in the letters. Whenever we find the letter on the top of the stack is same as the next letter on the linked list, start popping(and incrementing the linked list pointer) and set a count on the number of letters that matches. After we find a mismatch, push back all the letters that you popped from the stack, and continue your pushing and popping operations. The worst case complexity of this method would be O(n2) e.g. when the linked list is just a string of the same letters.
To improve on the space and time complexity(by some constant factors), I proposed copying the linked list to an array and finding the largest sized palindrome in the array which again takes O(n2) time complexity and O(n) space complexity.
Any better approach to help me with? :(
One could come up with a O(n²)-algorithm with O(1) space complexity as follows:
Consider f→o→b→a→r→r→a→b:
Walk through the list reversing the links while visiting. Start with x=f and y=f.next:
set x.next = null
f o→b→a→r→r→a→b
^ ^
| \
x y
and check for how many links both lists (x and y) are equal.
Now continue. (tmp=y.next, y.next=x, x=y, y=tmp)
E.g. in the second step, it will yield f←o b→a→r→r→a→b, with x=o and y=b, now you check again if it's a palindrome and continue:
f←o←b a→r→r→a→b
f←o←b←a r→r→a→b
f←o←b←a←r r→a→b yay :)
etc.
If you need to restore the list again, reverse it again in O(n)
This is a well analyzed problem with O(N) time complexity.
You can reverse the original string(let's say str and str_reversed)
Then the problem is transformed to: find the longest common substring in str and str_reversed.
An O(N) approach is building a suffix tree(O(N)) with constant time lowest common ancestor retrieval.
If you copy the lists to an array, the following could be useful: Since we consider only even-length-palindromes, I assume this case. But the technique can be easily extended to work wich odd-length-palindromes.
We store not the actual length of the palindrome, but half the length, so we know how many characters to the left/right we can go.
Consider the word: aabbabbabab. We are looking for the longest palindrome.
a a b b a b b a b a b (spaces for readability)
°^° start at this position and look to the left/right as long as possible,
1 we find a palindrome of length 2 (but we store "1")
we now have a mismatch so we move the pointer one step further
a a b b a b b a b a b
^ we see that there's no palindrome at this position,
1 0 so we store "0", and move the pointer
a a b b a b b a b a b
° °^° ° we have a palindrome of length 4,
1 0 2 so we store "2"
naively, we would move the pointer one step to the right,
but we know that the two letters before pointer were *no*
palindrome. This means, the two letters after pointer are
*no* palindrome as well. Thus, we can skip this position
a a b b a b b a b a b
^ we skipped a position, since we know that there is no palindrome
1 0 2 0 0 we find no palindrome at this position, so we set "0" and move on
a a b b a b b a b a b
° ° °^° ° ° finding a palindrome of length 6,
1 0 2 0 0 3 0 0 we store "3" and "mirror" the palindrome-length-table
a a b b a b b a b a b
^ due to the fact that the previous two positions hold "0",
1 0 2 0 0 3 0 0 0 we can skip 2 pointer-positions and update the table
a a b b a b b a b a b
^ now, we are done
1 0 2 0 0 3 0 0 0 0
This means: As soon as we find a palindrome-position, we can infer some parts of the table.
Another example: aaaaaab
a a a a a a b
°^°
1
a a a a a a b
° °^° °
1 2 1 we can fill in the new "1" since we found a palindrome, thus mirroring the
palindrome-length-table
a a A A a a b (capitals are just for emphasis)
^ at this point, we already know that there *must* be a palindrome of length
1 2 1 at least 1, so we don't compare the two marked A's!, but start at the two
lower-case a's
My point is: As soon as we find palindromes, we may be able to mirror (at least a part of) the palindrome-length table and thus infer information about the new characters.
This way, we can save comparisons.
Here is a O(n^2) algorithm:
Convert the list to a doubly linked list
To have an even length palindrome you need to have two same letters next to each other.
So iterate over each each pair of neighboring letters (n-1 of them) and on each iteration, if the letters are identical, find the largest palindrome whose middle letters are these two.
I did it by using recursion in O(n) time.
I am doing this by,
suppose we have a source linked list, now copy the entire linked
list to other linked list i.e. the target linked list;
now reverse the target linked list;
now check if the data in the source linked list and target linked list are equal, if they are equal they are palindrome,
otherwise they are not palindrome.
now free the target linked list.
Code:
#include<stdio.h>
#include<malloc.h>
struct node {
int data;
struct node *link;
};
int append_source(struct node **source,int num) {
struct node *temp,*r;
temp = *source;
if(temp == NULL) {
temp = (struct node *) malloc(sizeof(struct node));
temp->data = num;
temp->link = NULL;
*source = temp;
return 0;
}
while(temp->link != NULL)
temp = temp->link;
r = (struct node *) malloc(sizeof(struct node));
r->data = num;
temp->link = r;
r->link = NULL;
return 0;
}
int display(struct node *source) {
struct node *temp = source;
while(temp != NULL) {
printf("list data = %d\n",temp->data);
temp = temp->link;
}
return 0;
}
int copy_list(struct node **source, struct node **target) {
struct node *sou = *source,*temp = *target,*r;
while(sou != NULL) {
if(temp == NULL) {
temp = (struct node *) malloc(sizeof(struct node));
temp->data = sou->data;
temp->link = NULL;
*target = temp;
}
else {
while(temp->link != NULL)
temp = temp->link;
r = (struct node *) malloc(sizeof(struct node));
r->data = sou->data;
temp->link = r;
r->link = NULL;
}
sou = sou->link;
}
return 0;
}
int reverse_list(struct node **target) {
struct node *head = *target,*next,*cursor = NULL;
while(head != NULL) {
next = head->link;
head->link = cursor;
cursor = head;
head = next;
}
(*target) = cursor;
return 0;
}
int check_pal(struct node **source, struct node **target) {
struct node *sou = *source,*tar = *target;
while( (sou) && (tar) ) {
if(sou->data != tar->data) {
printf("given linked list not a palindrome\n");
return 0;
}
sou = sou->link;
tar = tar->link;
}
printf("given string is a palindrome\n");
return 0;
}
int remove_list(struct node *target) {
struct node *temp;
while(target != NULL) {
temp = target;
target = target->link;
free(temp);
}
return 0;
}
int main()
{
struct node *source = NULL, *target = NULL;
append_source(&source,1);
append_source(&source,2);
append_source(&source,1);
display(source);
copy_list(&source, &target);
display(target);
reverse_list(&target);
printf("list reversed\n");
display(target);
check_pal(&source,&target);
remove_list(target);
return 0;
}
First find the mid point of the linked list, for this traverse through the linked list and count the number of nodes.
Let's say number of nodes is N, mid point will be N/2.
Now traverse till the mid-point node and start reversing the linked list till the end which can be done in place with O(n) complexity.
Then compare the elements from start to midpoint with elements from mid-point to last if they all are equal, string is a palindrome, break otherwise.
Time Complexity :- O(n)
Space Complexity :- O(1)