Two Singly linked Lists, size m , r and want to insert the first linked list nodes after the head of the second linked list, and the time complexity has to be O(1) of the method.
This really an intereseting difficult problem for me. Eatch time I think of a solution, the Time complexity is O(m+r)
I need some hints to solve this. I consumed useless effort on this problem.
EDIT:
Let me share what I have so far:
Create a new Linked List
Add the HEAD of the 2nd list
Still O(1)
Add all the nodes of 1st list
Becomes (n)
Add the rest of the nodes from the 1st list
Becomes another (n-1)
UPDATE:
What do you think about this? I got inspired directly after I asked here :)
If you have two singly-linked lists and don't have the tail of the first already, this is only possible in O(n). If you have the tail you simply make it point to the head of the second list...
Edit: 2nd list head points to first list's head. Hold a reference to 2nd list's 2nd node. Iterate down first list - again this is O(n) if you don't have a reference to the tail to start - and have the tail of that point to the original 2nd element of the 2nd list.
Assuming you have these structures:
List
Head node
Tail node
Node
Value
Next node
Reminder to self: the goal is: "insert the first linked list nodes after the head of the second linked list".
Then all you've got to do is:
// Hook up the end of list1 to the original second element of list2
list1.tail.next = list2.head.next;
// Set the second element of list2 to be the first element of list1
list2.head.next = list1.head;
List2 still ends where it did before (its tail node is the same).
You've now got list1 with a "floating" head, which is generally bad news... but if you iterate over list1 you'll get all the elements from both original lists...
Related
I'm having trouble determining the Big-O notation of the following operations for both LinkedLists and ArrayLists:
traversal to middle of list
modification at middle of list
For ArrayLists, I think that traversal is an O(n) operation while modification is an O(1) operation, given the index. For LinkedLists, I think that both traversal and modification should be O(n).
I'm not sure if I'm right on either one of these structures, since the definition of "traversal" is a bit unclear to me. Does "traversal" mean "iteration"?
Thanks for your help in advance!
In general, traversal means iterating over the list. But if all you need is to get access to the middle element, you don't have to traverse.
Since an ArrayList is backed up by an array and you know the size of the list (array) and an array allows RandomAccess by an index, getting the middle element is O(1).
traversing to the middle of the list for an arraylist is O(1) - they're indexed. Given an arraylist of 5 million items, fetching the 2.5millionth item takes about as long as getting the 5th item from an arraylist of 10 items.
For linkedlist, it's O(n) - you aren't fetching the 2.5millionth item except by starting from the front and iterating one-by-one through each and every item in the list.
Insertion for arraylists is O(n) - to insert, you need to take all elements that are after it, and shift them up by one. Inserting an element in the middle of a 5-million large arraylist is going to take a lot longer than in the middle of a 10-item large arraylist; one requires moving 2.5 million items up by 1, the other only 5.
Insertion in the middle for linkedlists is O(1), you just tell the 'before' item that the 'next' is now the new one, and what used to be the 'before' item's 'next' now gets configured so that its 'prev' item is the newly added item; then the newly added item's 'prev' and 'next' point at those 2 nodes.
Of course, traversing to the right node in your linkedlist to this.. is O(n).
In my lecture noes its given that if doubly linked list is empty then
header.next==tail;
Or
tail.prev==header;
But I feel like this is the case when there's exactly two nodes. Shouldn't the empty case be
head==null.
I don't know if I am correct.I am sill new to this subject.Can someone please clarify this
There are two common ways to store a double linked-list:
Let head and tail refer to actual nodes in the tree.
head variable tail variable
| |
V V
first -> second -> third -> null
In this case, you are correct - head will be null.
Let head and tail be special nodes (called "sentinel nodes", as pointed out in the other answer) which don't actually contain any data and point to the first and last nodes in the list through next and prev respectively.
head variable tail variable
| |
V V
head -> first -> second -> third -> tail -> null
node node
In this case, header.next == tail will mean the list is empty.
One might use this approach instead of the above one to simplify the implementation a bit and make the code a bit faster - there's no need to make special provision for removing or inserting the first or last nodes.
This doubly-linked list is using both head and tail sentinel nodes. These are nodes that don't actually contain elements of the list, but help to make certain algorithms slightly nicer by making the head and tail cases work more like the middle of the list.
If the list weren't using sentinels, then the empty case would be head==null, and the two-element case would have header.next==tail and tail.prev==header.
I am thinking on the Algo to find the 3rd last element in the Singly Link List and I come up with one by myself(space in-efficient)
Put the Link List in a ArrayList using a loop with O(n)time complexity [a lot of space complexity]
then find the size of Arraylist and retrieve the element[required element] at (size-2) index location
Please guide me if my algo make sense
FYI
Other I searched is :
Put two pointers and keep 1st pointer on 1st element and 2nd pointer on 3rd element and move them parallel
When the second pointer reaches the end of LinkList, retrieve the node[required node] which is pointed by the 1st pointer
Use two pointers: pointer-1 and pointer-2
make pointer-1 points to third node in single linked list.
pointer-1 = node1->next->next; // point to 3rd nd
node1-->node2-->node3-->node4---> ...... -->node-last
^
|
pointer-1
Now set pointer-2 points to first-node
pointer-2 = node1; // point to 1st nd
node1-->node2-->node3-->node4---> ...... -->node-last
^ ^
| |
pointer-2 pointer-1
Now, travel in linked list in a loop till pointer-1 points to last node, in loop also update pointer-2 (every time to next node of itself )
while (pointer-1->next!=NULL){// points to last node
pointer-1 = pointer-1 -> next;
pointer-2 = pointer-2 -> next;
}
When loop ends pointer-1 points to last-node, pointer-2 points to third last
node1-->node2-->........ ->node-l3-->node-l2-->node-last
^ ^
| |
pointer-2 pointer-1
It works in O(n) times, where n is number of nodes in linked-list.
Since the linked list is singly linked, you need to traverse it from the beginning to end to know what the 3rd to last element is, os O(n) time is unavoidable (unless you maintain a pointer to the 3rd to last element in your linked list).
Your 2 pointers idea, will use constant space. This is probably the better option, since creating an ArrayList will have more overhead, and use more space.
Get two pointers. pA, pB
Move pA to 3 elements advance and pB to the head:
1->2->3->4-> .... ->99->100
| |
pB pA
After this, move both pointers in the same loop till pA reaches to the last element.
At that point pB will be pointing to the last 3rd element
1->2->3->4-> .... ->98->99->100
| |
pB pA
Edited:
traversal will be one:
while(pA->next!=null){
pA = pA->next;
pB = pB->next;
}
Here pB will be 3rd last
An alternative view to solve this even though it is O(n)
Create an empty array(n), start a pointer into this array at 0, and start from the beginning of the linked list as well. Every time you visit a node store it in the current index of the array and advance the array pointer. Keep filling the nodes in the array, and when you reach the end of the array please start from the beginning again so as to overwrite.
Now once you end the final end of the list the pointer nth elemtn from end :)
In practice, a Java LinkedList keeps track of its size, so you could just go to 'list.get(list.size()-2)', but with a constructed linked list, I'd do the following:
Keep an array of 3 values. As you traverse the list, add the update the value at array[i%3]. When there are no more values, return the value at array[(i-2)%3].
The first thing I'd do is ask you to reconsider your use of a singly linked list. Why not just store your data in an ArrayList? It does everything you seem to want, and it's a builtin so it's relatively efficient compared to what most people would write.
If you were bound and determined to use a linked list, I'd suggest keeping a direct pointer to the 3rd last element (tle). Insertions are easy - if they come before the tle, do nothing; if after, advance the tle pointer to the tle's next. Removals are more of a hassle, but probably not most of the time. If the removal occurs before the tle, it's still the tle. The annoying situation is if the element to be removed is the tle or later, in which case you get to iterate through from the beginning until the next() reference of the current node is the tle. The current node will become the new tle, and you can then proceed with the removal. Since there are only three nodes which invoke this level of work, you'll probably do all right most of the time if the list is sizable.
A final option, if removals from the end are a frequent occurrence, is to maintain your list from back to front. Then the tle becomes the third from the front for maintenance purposes.
//We take here two pointers pNode and qNode both initial points to head
//pNode traverse till end of list and the qNode will only traverse when difference
// between the count and position is grater than 0 and pthNode increments once
// in each loop
static ListNode nthNode(int pos){
ListNode pNode=head;
ListNode qNode=head;
int count =0;
while(qNode!=null){
count++;
if(count - pos > 0)
pNode=pNode.next;
qNode=qNode.next;
}
return pNode;
}
If I have created a linked list where order of insertion is 5,4,3. I use the head reference so the linked list gets stored as 3->4->5->null.
When I want to reverse the linked list == original order of insertion so it will be
5->4->3->null. Now if this is how my new list looks like, which node should my head reference be referring to so the new elements I add to the list will still have O(1) insertion time?
I think head, by definition, always points to the first element of a list.
If you want to insert to the end of a linked list in O(1) then keep two references, one to the first element and one to the last element. Then adding to the end is done by following the last reference to the last element, add the new element beyond the last element, update the last reference to point to the new last element.
Inserting to an empty list becomes a special case because you have to set both first and last references not just the last reference. Similarly for deleting from a list with one element.
If you want to the back of a singly linked list, you should keep a reference to the last element. When you want to insert a new element, you create a new link object with the new element as head, the tail of the element you insert it after as the tail, and the new link object as the new tail of the element you insert it afterward. This takes three pointer movements and thus constant time.
For any linked list to have an O(1) insertion time, you have to insert into the front of the list or some other arbitrary location completely disregarding any order. Being a singly linked list means that you can't point to the last element in the list because the list up until the last element will be inaccessible. A fix to this might be as Shannon Severance has stated in that you keep two pointers, a head and a tail. You can use the head to access the elements and the tail to arbitrarily add elements to the list.
Think of it this way:
The reverse of a list consisting of HEAD -> [the rest of the list] is precisely: reverse([the rest of the list]) -> HEAD.
Your base case would be if the list contains a single element. The reverse of such a list is just itself.
Here's an example (using executable pseudo-code, aka Python):
class Node(object):
def __init__(self, data, next_=None):
self._data = data
self._next = next_
def __str__(self):
return '[%s] -> %s' % (self._data,
self._next or 'nil')
def reverse(node):
# base case
if node._next is None:
return node
# recursive
head = Node(node._data) # make a [HEAD] -> nil
tail_reverse = reverse(node._next)
# traverse tail_reverse
current = tail_reverse
while current._next is not None:
current = current._next
current._next = head
return tail_reverse
if __name__ == '__main__':
head = Node(0,
Node(1,
Node(2,
Node(3))))
print head
print reverse(head)
Note that this is not in O(1) due to the lack of a last-element reference (only HEAD).
In java LinkedLists, we have iterators.
I can use a ListIterator and then do a linear search to find the last element that the Iterator points to. But It will take O(n) time. How can I find an Iterator that points to the last element in O(1) time?
The java.util.LinkedList is actually the doubly-linked variant. It can traverse from both ends. Hence, getting the first and getting the last element are equally fast.
At least this is the case with Sun's (Oracle's?) implementation.
I'm not sure if this is O(1), but if you really want an iterator to the last element (instead of just getting the last element), you can use the listIterator(index) method, where index is the position in the list you want the iterator to start from.
By definition of Linked List, there is a pointer only to the head or first item and access to every other node is possibly only sequentially! So I am afraid the answer is NO! There is no way you can access the last element in O(1) time. You could put the linked-list contents into an array or map and then the next access could be O(1)