Nov 8, 2009
Pages: 1, 2

Data Structures -- Linked List - Find the nth last element in linked list.

free web hosting

Read Latest Entries..: (Post #14) by iGuest on Aug 28 2009, 12:49 PM.
main class problem.. Data Structures -- Linked List hello..It's my first time here to visit..I want to ask for help in making a main class of my linked list in queue..Here's what is asking for:   If the input satisfies partial ordering, then the algorithm will terminate when the Queue is empty – If a loop exists, it will also terminate but will not output the elements in the Loop. Instead, it will just inform the user that a loop is present:   here's the code: interface Queue{ ...
read more.
Read the FIRST post of this Topic. - Express your Opinion! Contribute Knowledge :-).

Open Discussion > MODERATED AREA > Computers > Programming Languages > Others

Data Structures -- Linked List - Find the nth last element in linked list.

varalu
Given a linked list, find the 5th last element with Time complexity O(n) and minimal space complexity.

Note: If you know the answer and if you feel it is simple also please post the answers so that others will come to know about the answers.

What is a linked list?? /* this is for your further reference and reading */
QUOTE
In computer science, a linked list is one of the fundamental data structures, and can be used to implement other data structures. It consists of a sequence of nodes, each containing arbitrary data fields and one or two references ("links") pointing to the next and/or previous nodes. The principal benefit of a linked list over a conventional array is that the order of the linked items may be different from the order that the data items are stored in memory or on disk, allowing the list of items to be traversed in a different order. A linked list is a self-referential datatype because it contains a pointer or link to another datum of the same type. Linked lists permit insertion and removal of nodes at any point in the list in constant time, but do not allow random access. Several different types of linked list exist: singly-linked lists, doubly-linked lists, and circularly-linked lists.
There are various kinds of linked lists available and can be implemented in many languages and in different ways.

Applications of Linked Lists
QUOTE
Linked lists are used as a building block for many other data structures, such as stacks, queues and their variations.

The "data" field of a node can be another linked list. By this device, one can construct many linked data structures with lists; this practice originated in the Lisp programming language, where linked lists are a primary (though by no means the only) data structure, and is now a common feature of the functional programming style.

Sometimes, linked lists are used to implement associative arrays, and are in this context called association lists. There is very little good to be said about this use of linked lists; they are easily outperformed by other data structures such as self-balancing binary search trees even on small data sets (see the discussion in associative array). However, sometimes a linked list is dynamically created out of a subset of nodes in such a tree, and used to more efficiently traverse that set.



even bad solutions are welcome... smile.gif.

 

 

 


Comment/Reply (w/o sign-up)

pointybirds
Hmm, presuming a singly linked list where you can't start at the end and work your way back, you could use a circular buffer with 5 elements (e.g. an array that can store the contents of the LL nodes) and traverse the list until you reach the end ... then, the "next" element in your circular buffer is the fifth last.

E.g.:

for (i=0; (e = next element) != null; i++%5) {
buf[i] = e
}
fifth_last = buf[i]

Something like that I guess. You'd also need to initialise your array to null and check for this at the end in case your LL < 5 elements.

Comment/Reply (w/o sign-up)

varalu
yours is a nice solution... Better in usage of memory also. This circular buffer thing is very good.
What is i am giving you a constraint of
1. "NO EXTRA MEMORY"
2. No additional Data structures.

Give a solution with the above constraints.

Small Hint:
Do not make it complex...think very simple. --> for a simple solution.

Comment/Reply (w/o sign-up)

sanjay0828
Ok.. here is a very simple solution

Have two pointers.

Initially, let both the pointers point to the first node of the linked list

Now move one of the pointers to the 5th node of the linked list.
This can be done in O(1) complexity i.e. constant time.

Example:-
1-->2-->3-->4-->5-->6-->7-->8-->9-->10->11-->12

Here, one pointer points to 5 while the other pointer points to 1

Now keep moving each pointer i.e. current node to next node, until the first pointer reaches the end of the linked list i.e. 12
The second pointer will now be pointing to the 5th last element i.e. 8

Comment/Reply (w/o sign-up)

jlhaslip
$item= $array[count($array)-5];

untested

may need to perform this in steps though

$num = count($array);
$n = $num - 5;
$item = $array[ $n ];


Comment/Reply (w/o sign-up)

varalu
@sanjay0828
Good one... the expected solution.

Again... i want a simpler solution. What will be the basic answer that comes to your mind if i give this problem.??
Very basic.. smile.gif..

If no answer i will be posting it in my next post.

Comment/Reply (w/o sign-up)

FeedBacker
Use two variable (sum4 and sum5) to store the sum of last 4 nodes and last 5 nodes respectively. At the end of the loop, the 5th node data = sum5 - sum4.

-Grant

Comment/Reply (w/o sign-up)

totrap
while(ptr->next->next->next->next->next!=NULL)
ptr=ptr->next;

//after loop, ptr points to the fifth last element in the list;

Comment/Reply (w/o sign-up)

songs2enjoy
reverse the list and find the 5th element from the start,

Not simple though just an idea.

Varalu,

Can u plz post what's the simple idea ?

Thanks

Comment/Reply (w/o sign-up)

iGuest-Saugata Kanti Sarkar
How to find the number of element in circular link list
Data Structures -- Linked List

Hi All,
If I have a circular link list and I want to count the no of element within it.I donot want to use first_pointer==last_pointer method.
Is there any other approach to count the element?

Thanks
Sarkar

-reply by Saugata Kanti Sarkar

Comment/Reply (w/o sign-up)

Latest Entries

iGuest
main class problem..
Data Structures -- Linked List

hello..It's my first time here to visit..I want to ask for help in making a main class of my linked list in queue..Here's what is asking for:

  If the input satisfies partial ordering, then the algorithm will terminate when the
Queue is empty
– If a loop exists, it will also terminate but will not output the elements in the
Loop. Instead, it will just inform the user that a loop is present:

 

here's the code:

interface Queue{

    /* Insert an item */
    void enqueue(Object item) throws QueueException;

    /* Delete an item */
    Object dequeue() throws QueueException;
}


Class QueueException extends RuntimeException{
    public QueueException(String err){
        super(err);
    }
}

 

another file:

class LinkedQueue implements Queue{
    Node front, rear;

    /* Create an empty queue */
    LinkedQueue(){
    }

    /* Create a queue with node and initially */
    LinkedQueue(Node and){
        front = and;
        rear = and;
    }

    /* Inserts an item onto the queue */
    public void enqueue(Object item){
        Node and = new Node(item, null);
        if (front == null) {
            front = and;
            rear = and;
        }
        else{
            rear.Link = and;
            rear = and;
        }
    }

    /* Deletes an item from the queue */
    public Object dequeue() throws QueueException{
        Object x;
        if (front == null) throw new QueueException
                        ("Retrieving from an empty queue.");
            x = front.Info;
        front = front.Link;
        return x;
    }

    /* Main method to test the queue */
    public static void main(String args[]){
        LinkedQueue q = new LinkedQueue();
        for (int I=11; I>0; I--){
            q.Enqueue(new Integer(I));
            System.Out.Println(I +" inserted");
        }
        for (int I=12; I>0; I--)
            System.Out.Println(q.Dequeue() + " retrieved");
    }

}

thank you...God Bless 

-reply by cathelyn

Comment/Reply (w/o sign-up)

vivek.m
QUOTE
But the answer that i expected is below..
Just scan the list twice.
You can get the kth element from the last.


This algorithm is known as hare and tortoise algorithm.



That's same as what I said... In first scan, find the length and in second scan, find the required element. This seems to be only tortoise-tortoise scan.
The other answer (your and sanjay's answer) is more efficient with worst case operations half of what is required in first answer. complexity will be o(n) in both cases. (my bad. i had to edit. i mentioned complexity o(n^2) incorrectly.)

Thanks for the problem.

Comment/Reply (w/o sign-up)

varalu
QUOTE(vivek.m @ Nov 24 2008, 08:27 PM) *
the most basic and the only answer that came to my mind (actually, my frnd's mind. I am too laazy to use mine)  is to find length and then to find the (l-n)th element with o(n2) complexity.
i am interested in your answer.. it's more than a month since you posted your question.  blush.gif


Ok.. here is my answer...

This is similar to finding the middle element in the link list with slight variation..

1. Have two pointer initially ( first and second )
2. move the second pointer alone 5 nodes.
3. Now move both the pointers one node at a time until the second reaches the end.
when the second reaches the end , the first node will be the 5th last element..


CODE
node * first ,*second;

first = second = root;

// moves the second ptr 5 nodes..
int i =0;
while ( (i < 5) && (second != NULL) )
{
    second = second-> next;
    i++;
}

while( second->next != NULL )
{
       first = first->next;
       second = second->next;
}

return (first) ; // first ptr is the 5th node from the last..


The above solution is same as the one Sanjay gave. This algorithm can be even generalized to find the kth node from the last similarly....

But the answer that i expected is below..

Just scan the list twice.
You can get the kth element from the last.


This algorithm is known as hare and tortoise algorithm.

Comment/Reply (w/o sign-up)

vivek.m
QUOTE(varalu @ Oct 27 2007, 09:09 AM) *
@sanjay0828
Good one... the expected solution.

Again... i want a simpler solution. What will be the basic answer that comes to your mind if i give this problem.??
Very basic.. smile.gif ..

If no answer i will be posting it in my next post.


the most basic and the only answer that came to my mind (actually, my frnd's mind. I am too laazy to use mine)  is to find length and then to find the (l-n)th element with o(n2) complexity.


i am interested in your answer.. it's more than a month since you posted your question.  blush.gif


Comment/Reply (w/o sign-up)



Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

This textarea will convert to Rich-Text automatically (IE, Firefox, Chrome)

Pages: 1, 2
Similar Topics

Keywords : data, structures, linked, list, nth, element, linked, list,

  1. Data Structure -- Permutations
    (1)
  2. Data Structure -- Queue -- Implement Using Stack
    (1)
    Implement a Queue using a stack. No restriction on space complexity. One possible Solutions a
    costly procedure... 1. Use a temp stack 2. Insertion into queue - Push the element into the
    original stack 3. Deletion from queue - Pop all the elements from stack into a temp stack
    - pop out the first element from the temp stack - pop all the remaining elements back to the
    original stack What is a queue? QUOTE A queue is a particular kind of collection in which
    the entities in the collection are kept in order and the principal (or only) operation....
  3. Data Structure -- Trees -- Threaded Binary Tree
    (2)
    A binary tree having a loop is known as a threaded binary tree. Have a look at the attachment to
    have an idea of a threaded binary tree.... A's right child is B and B's left child is A.
    Write an algorithm to find out whether the given tree is a threaded binary tree. Look for time
    and space complexity.....
  4. Data Structures -- Expression Trees
    (0)
    Construct an expression tree for the expression (a || /cool.gif" style="vertical-align:middle"
    emoid="B)" border="0" alt="cool.gif" /> && (c || d) After constructing the tree convert the tree to
    correspond to the associative property of the given expression. Eg: (1 + 2) * ( 3 + 4) = (1 * 3) +
    (1 * 4) + (2 * 3) + (2 * 4) Similar to that, from the constructed expression tree, construct a new
    expression tree such that inorder traversal of the new tree will be associative value of the given
    expression Inorder traversal of the new tree should be (a && c) || (a && d) || (....
  5. Data Structure -- Arrays -- Odd Number Of Elements
    (0)
    Given an array of elements with many numbers occurring even number of times and two numbers
    occurring odd number of times. Find out the two numbers that occur odd number of times. example:
    Elements in array -- 14433446 The expected result is 1 and 6 One solution 1. Find max of the
    array 2. Hash Function : element/max value 3. Repeat to all elements... 4. Find frequency... yo will
    get the 2 elements with odd frequency. but this is not the optimal.... Do find more solutions to
    this and post it. Look for time and space complexity. Another Solution one more s....
  6. Data Structures -- String -- Arrange Based On Repetition
    String data structure (2)
    Consider a string with any number of elements occurring any number of time. Rearrange the string
    in such a way that the alphabet with most occurrence occurs in the followed by the next most
    occurring alphabet and so on... It should also be seen that the alphabets should occur frequency
    number of times. Example: Input : abcdaeghzabcdbhb Output : bbbbaaaccddhhegz ....
  7. Data Structures -- Linked List -- Point Of Merging
    (4)
    Given two singly linked lists with both of them merging at some point. Find the position at which
    they merge. Eg: 1->30->50->65->2->59 88->46->65->2->59
    The above two linked lists merge at 65. Find this node where they merge.. Question
    Courtesy: Antony(Friend) One possible Answer A simple answer would be to find the length of
    both the linked lists and have two pointers, one for each linked list. Move (difference in lengths)
    steps in the longer linked lists and then start moving both the pointers by one every t....
  8. Data Structures -- String -- Palindrome
    Check if a string is a palindrome... (6)
    Write an algorithm to check whether a given string is palindrome or not in time complexity O(n)
    What is a palindrome?? QUOTE A palindrome is a word, phrase, number or other sequence of units
    that has the property of reading the same in either direction (the adjustment of punctuation and
    spaces between words is generally permitted). Composing literature in palindromes is an example of
    constrained writing. The word "palindrome" was coined from Greek roots palin
    (πάλιν; "back") and dromos (δρóμος; "way,
    direction") by....
  9. Data Structures -- Linked List -- Reverse
    Reverse a linked list (9)
    Give an algorithm to reverse a linked list with a time complexity of O(n) and minimal space
    complexity. What is a linked list? Search trap17.com. i Have already answered this question in
    one of my older questions. Solution 1 Here is one simple solution... CODE Void
    ReverseList(node* head) {     node *temp,*current,*result;     temp=null;     result=null;
        current=head;     while(current!=null)     {         temp=current->next;
            current->next=result;         result=current;         current=temp;     }    head=result;
    The above was suggested by m....
  10. Data Structures -- Binary Tree -- Structurally Same
    Find if 2 binary tress are structurally same?? (5)
    Given two binary trees, find out whether a tree is structurally same to the other. Structurally same
    means that the two trees look alike or a tree looks alike a subtree of the other tree. Look for
    time and space complexity. Some more for readers What is a binary tree? QUOTE A binary
    tree is made of nodes, where each node contains a "left" pointer, a "right" pointer, and a data
    element. The "root" pointer points to the topmost node in the tree. The left and right pointers
    recursively point to smaller "subtrees" on either side. A null pointer represents a binary....
  11. Data Structures -- Binary Tree -- Mirror Image
    Binary Tree -- Mirror Image (3)
    Given a binary tree, write an algorithm to find its mirror image with minimal time and space
    complexities. Note: If you know the answer and if you feel it is simple also please post the
    answers so that others will come to know about the answers. This question was sent by my friend
    through mail. Solutions Suggested Sol 1 CODE void PrintMirror(node *root) {
        if(node!=NULL)        PrintMirror(root->right);     Printf(root->data);
        PrintMirror(root->left);      } In case of implementation using array 2i+1 stores left child
    of ith node and 2i+2 store....
  12. Data Structure Questions
    (5)
    Question 1 Reply the solutions if you have any so that we can discuss... Given an array of n
    elements (containing only positive numbers) and sum, X. Find the first two elements in the array
    that sum upto X eg: Array of elements - {2, 3,1000, 200, 51, 88, 29, 49, 65, 40, 98, 12, 3}
    Sum - 100. The answer for the above sample is 51, 49. There are other possiblities
    also, but the first two numbers summing upto the given sum, 100 should be taken. How will you do
    this with minimal space and time complexities? Question 2 Given two nodes of ....
  13. Limiting Returned Data To Last X Fields With Sql
    (2)
    Hello, I'm currently developing a social-networking site in ColdFusion and several aspects of
    the site require me to return a limited number of records for display (e.g. displaying the last 3
    news items in the left-hand column on the front page, etc.). I currently only have a small SQL
    "cheet sheet" and what my ColdFusion reference book tells me, and I cannot find anything anywhere
    about limiting the data returned from a SELECT statement to the last X number of records. Any help
    is appreciated! Thanks, zeeman48....
  14. A Question About Data Collecting Program
    usually found in registers (1)
    does anyone know which programming language is used to make applications like those used in shops
    and malls where the sales assistant will enter name of a product and all its details will come up
    and whn someone makes a purchase the details will go to a database , i need to know which language
    is used and also which platform is used ,thanks in advance /laugh.gif"
    style="vertical-align:middle" emoid=":lol:" border="0" alt="laugh.gif" /> Please read the rules.
    The What Is..? forum is for answering a common question or telling everybody about what
    interesting fact you ....

    1. Looking for data, structures, linked, list, nth, element, linked, list,

Searching Video's for data, structures, linked, list, nth, element, linked, list,
See Also,
advertisement


Data Structures -- Linked List - Find the nth last element in linked list.

Affordable Web Hosting, Low cost Web Hosting - ComputingHost.com