473,783 Members | 2,269 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Linked list Question

MJ
Hi
I have a question
I have a singly linked list of 10 elements. I have to find the Nth (Ex
3rd element from the end) element from the end. What are the ways to
do it with less complexity
I have two methods
1. Reverse the linked list and than travese till the Nth location
2. Find the total no of elements in the list and than find the Nth node
postion form the start
both these methods will take complexity more than n + some complexity

other methods are most welcome
MJ

Nov 14 '05 #1
8 6823
And how is this on topic for comp.lang.c?

Nov 14 '05 #2

MJ wrote:
Hi
I have a question
I have a singly linked list of 10 elements. I have to find the Nth (Ex 3rd element from the end) element from the end. What are the ways to
do it with less complexity
I have two methods
1. Reverse the linked list and than travese till the Nth location
2. Find the total no of elements in the list and than find the Nth node postion form the start
both these methods will take complexity more than n + some complexity

other methods are most welcome
MJ


its OT but i'll answer,
take 2 pointers say
list *ahead, *curr;
i) now move ahead to nth element from head.
ii) put curr on first element.
iii) move both curr and ahead till ahead reaches the end of the list,
now curr points to the element required.

hope it helps.

Nov 14 '05 #3

MJ wrote:
Hi
I have a question
I have a singly linked list of 10 elements. I have to find the Nth (Ex 3rd element from the end) element from the end. What are the ways to
do it with less complexity
I have two methods
1. Reverse the linked list and than travese till the Nth location
2. Find the total no of elements in the list and than find the Nth node postion form the start
both these methods will take complexity more than n + some complexity

other methods are most welcome
MJ


FYI, comp.programmin g is usually a better place to ask generic
algorithm
questions as opposed to questions about C in particular.

You could put pointers to the list elements into an array and have
random access. Fine for the problem stated above. Not so good if you
are going to change the contents of the list.

-David

Nov 14 '05 #4
"Darius" <ra**********@g mail.com> wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .

MJ wrote:
Hi
I have a question
I have a singly linked list of 10 elements. I have to find the Nth

(Ex
3rd element from the end) element from the end. What are the ways to do it with less complexity
I have two methods
1. Reverse the linked list and than travese till the Nth location
2. Find the total no of elements in the list and than find the Nth

node
postion form the start
both these methods will take complexity more than n + some complexity
other methods are most welcome
MJ


its OT but i'll answer,
take 2 pointers say
list *ahead, *curr;
i) now move ahead to nth element from head.
ii) put curr on first element.
iii) move both curr and ahead till ahead reaches the end of the list,
now curr points to the element required.

hope it helps.


It's a common interview question. You just helped some bonehead get a
job he's not qualified for. Thank you for playing.

<rant>It don't understand why you guys help kids cheat on homework, and
"off-shore personnel" steal jobs, when it hurts your neighbors, makes
programmers a commodity item, and takes jobs away from people who can
really perform by giving them to idiots who cheat and steal.</rant>

--
Mabden
Nov 14 '05 #5
Mabden wrote:
"Darius" <ra**********@g mail.com> wrote in message
MJ wrote:

I have a singly linked list of 10 elements. I have to find the
Nth (Ex 3rd element from the end) element from the end. What are
the ways to do it with less complexity
I have two methods
1. Reverse the linked list and than travese till the Nth location
2. Find the total no of elements in the list and than find the
Nth node postion form the start
both these methods will take complexity more than n + some
complexity

other methods are most welcome


its OT but i'll answer,
take 2 pointers say
list *ahead, *curr;
i) now move ahead to nth element from head.
ii) put curr on first element.
iii) move both curr and ahead till ahead reaches the end of the
list, now curr points to the element required.


It's a common interview question. You just helped some bonehead
get a job he's not qualified for. Thank you for playing.

<rant>It don't understand why you guys help kids cheat on homework,
and "off-shore personnel" steal jobs, when it hurts your neighbors,
makes programmers a commodity item, and takes jobs away from people
who can really perform by giving them to idiots who cheat and steal.
</rant>


You're answering something from months ago. However there is
another useful way, and the problem is amusing. Create an array of
pointers of size N, where N is the distance from the end required.
Prefill it with NULLs. Now scan the list, inserting a copy of each
pointer in the array advancing the array index modulo N after
insertion. When you reach the end of the list the current array
position (which would be filled and advanced from if the end had
not been reached) either holds NULL, and the list is shorter than
N, or it holds the pointer to the end-Nth item.

After all that I realize that i am in c.l.c and the whole thing is
OT anyhow. So to bring it on topic I propose some code:

/* assuming suitable definition of node with a next field */
node *findlastbut(un signed int n, node *root)
{
node *lastn;
unsigned int ix;

n++;
if (!(lastn = malloc(n * sizeof *lastn))) return NULL;
for (ix = 0; ix < n; ix++) lastn[ix] = NULL;
ix = 0;
while (root) {
lastn[ix] = root;
root = root->next;
ix = (ix + 1) % n;
}
root = lastn[ix];
free(lastn);
return root;
} /* findlastbut, untested */

This could actually be an application for C99 flexible arrays.
This minimizes list accesses and never modifies the list.
Therefore, if the malloced memory is available, I claim this is the
optimum algorithm.

For some environments the modulo advance of ix could be
advantageously replaced by:

if (++ix >= n) ix = 0; /* note obfuscative self-healing */

or the while loop could be converted into a for for further
obfuscation.

--
Some informative links:
news:news.annou nce.newusers
http://www.geocities.com/nnqweb/
http://www.catb.org/~esr/faqs/smart-questions.html
http://www.caliburn.nl/topposting.html
http://www.netmeister.org/news/learn2quote.html
Nov 14 '05 #6
CBFalconer wrote:
.... snip ...
After all that I realize that i am in c.l.c and the whole thing is
OT anyhow. So to bring it on topic I propose some code:

/* assuming suitable definition of node with a next field */
node *findlastbut(un signed int n, node *root)
{
node *lastn;
unsigned int ix;

n++;
if (!(lastn = malloc(n * sizeof *lastn))) return NULL;
for (ix = 0; ix < n; ix++) lastn[ix] = NULL;
ix = 0;
while (root) {
lastn[ix] = root;
root = root->next;
ix = (ix + 1) % n;
}
root = lastn[ix];
free(lastn);
return root;
} /* findlastbut, untested */


It is now tested, and the declaration of lastn should be:

node **lastn;

--
Some informative links:
news:news.annou nce.newusers
http://www.geocities.com/nnqweb/
http://www.catb.org/~esr/faqs/smart-questions.html
http://www.caliburn.nl/topposting.html
http://www.netmeister.org/news/learn2quote.html

Nov 14 '05 #7
"CBFalconer " <cb********@yah oo.com> wrote in message
news:42******** *******@yahoo.c om...
CBFalconer wrote:

... snip ...

It's a common interview question. You just helped some bonehead
get a job he's not qualified for. Thank you for playing.

<rant>It don't understand why you guys help kids cheat on homework,
and "off-shore personnel" steal jobs, when it hurts your neighbors,
makes programmers a commodity item, and takes jobs away from people
who can really perform by giving them to idiots who cheat and steal.
</rant>


Nov 14 '05 #8
Mabden wrote:
"CBFalconer " <cb********@yah oo.com> wrote in message
CBFalconer wrote:

... snip ...

It's a common interview question. You just helped some bonehead
get a job he's not qualified for. Thank you for playing.

<rant>It don't understand why you guys help kids cheat on homework,
and "off-shore personnel" steal jobs, when it hurts your neighbors,
makes programmers a commodity item, and takes jobs away from people
who can really perform by giving them to idiots who cheat and steal.
</rant>


I wrote nothing of the sort. Please keep your attributions
accurate.

--
Some informative links:
news:news.annou nce.newusers
http://www.geocities.com/nnqweb/
http://www.catb.org/~esr/faqs/smart-questions.html
http://www.caliburn.nl/topposting.html
http://www.netmeister.org/news/learn2quote.html
Nov 14 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
15133
by: Kent | last post by:
Hi! I want to store data (of enemys in a game) as a linked list, each node will look something like the following: struct node { double x,y; // x and y position coordinates struct enemy *enemydata; // Holds information about an enemy (in a game) // Its a double linked list node
19
13576
by: RAJASEKHAR KONDABALA | last post by:
Hi, Does anybody know what the fastest way is to "search for a value in a singly-linked list from its tail" as oposed to its head? I am talking about a non-circular singly-linked list, i.e., head and tail are not connected. Of course, recursive function aproach to traverse the list is one way. But, depending upon the list size, it could overrun the stack pretty fast.
7
2614
by: Kieran Simkin | last post by:
Hi all, I'm having some trouble with a linked list function and was wondering if anyone could shed any light on it. Basically I have a singly-linked list which stores pid numbers of a process's children - when a child is fork()ed its pid is added to the linked list. I then have a SIGCHLD handler which is supposed to remove the pid from the list when a child exits. The problem I'm having is that very very occasionally and seemingly...
12
15100
by: Eugen J. Sobchenko | last post by:
Hi! I'm writing function which swaps two arbitrary elements of double-linked list. References to the next element of list must be unique or NULL (even during swap procedure), the same condition should be kept for references to previous element of list. Here is my solution below: struct node {
57
4303
by: Xarky | last post by:
Hi, I am writing a linked list in the following way. struct list { struct list *next; char *mybuff; };
2
1493
by: Paminu | last post by:
I have a Linked-List and would like to create pointers to elements in this list. e.g I would like two pointers that point to each of their elements in the Linked-List. But there should always be exactly 5 nodes between these pointers. Does this make any sense or are there some more efficient way to access certain elements in a Linked-List?
12
3954
by: joshd | last post by:
Hello, Im sorry if this question has been asked before, but I did search before posting and couldnt find an answer to my problem. I have two classes each with corresponding linked lists, list1 and list2, each node within list1 has various data and needs to have a pointer to the corresponding node in list2, but I cant figure out how to do this. Could someone explain what I might be missing, or maybe point me in the direction of a good...
9
2846
by: william | last post by:
When implementing Linked list, stack, or trees, we always use pointers to 'link' the nodes. And every node is always defined as: struct node { type data; //data this node contains ... node * nPtr; //the next node's pointer }
2
1700
by: phiefer3 | last post by:
Ok, first of all I'm not sure if this is the correct forum for this question or not. But hopefully someone can help me or at least point me in the direction of the forum this belongs. First of all, I am using C++, however it's managed C++ or visual C++, or whatever microsoft calls it. I'm using MSVS2005, and working on a Windows Forms Application project from the C++ projects tab. I'm pointing this out because apparently the syntax used in...
11
2554
by: Scott Stark | last post by:
Hello, The code below represents a singly-linked list that accepts any type of object. You can see I'm represting the Data variable a System.Object. How would I update this code to use generics instead of System.Object. I want the code in Form1_Load to remain exactly the same, but in the background I want to use generics. I'm trying to get a better understanding of how it works and I'm a little stuck.
0
9643
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10313
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10081
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8968
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6735
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3643
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2875
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.