Jump to content
xisto Community
varalu

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

Recommended Posts

import java.Util.LinkedList;public class LinkedListDelete {  public static void main(String args[]) {   LinkedList<String> ll = new LinkedList<String>();   ll.Add("B");   ll.Add("C");   ll.Add("D");   ll.Add("E");   ll.Add("F");   ll.AddLast("Z");   ll.AddFirst("A");   ll.Add(1, "A2");   System.Out.Println("Original contents of ll: " + ll);   ll.Remove("F");   ll.Remove(2);   System.Out.Println("Contents of ll after deletion: " + ll);   ll.RemoveFirst();   ll.RemoveLast();   System.Out.Println("ll after deleting first and last: " + ll);   String val = ll.Get(2);   ll.Set(2, val + " Changed");   System.Out.Println("ll after change: " + ll);  }}

Share this post


Link to post
Share on other sites

hai incase of doubly circle linked list we can traverse from startptr and endptr so if two traversals are done same time we can get the element in o(n/2) complexity
algorithm is

  startptr=head->llink;endptr= head->rlink;while(startptr!=endptr){if(head->llink!=NULL&&head->rlink!=NULL)  {	startptr=startptr->next;	endptr= endptr->llink;	 while(endptr->llink!=endptr->rlink)	 {	   if(endptr->info==key)		{		  printf("key is found",endptr->info);			}		 else			{			   endptr=endptr->llink;			   if(endptr->llink->llink!=NULL)			  {				printf("element is found %d"endptr->next->info);				 }			    startptr=startptr->rlink;	endptr= endptr->llink;	 while(startptr->llink!=startptr->rlink)	 {	   if(startptr->info==key)		{		  printf("key is found",startptr->info);			}		 else			{			   startptr=startptr->rlink;			   if(startptr->rlink->rlink!=NULL)			  {				printf("element is found %d",statptr->rlink->info);				 }

hai buddy i think if you execute this code you can find 5 th element in o(n/2) complexity
but the linked list must be circularlinkedlist thanks

bye
Edited by velma (see edit history)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.