473,406 Members | 2,705 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

reverse a link list

Neo
Hi Frns,

Could U plz. suggest me how can i reverse a link list (without recursion)???

here is my code (incomplete):

#include<stdio.h>

#include<stdlib.h>

#define MAX_NODES 8

typedef struct node {

int data;

struct node *next;

} NODE;

void reverse_list(NODE **head)

{

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

/* TODO: Reverse the List here. */

/* ___________________________ */
return;

}

int main()

{

NODE *head, *tmp;

int i;

head = malloc(sizeof(NODE));

if(!head) return 1;

head->data = 1;

head->next = NULL;

tmp = head;

for(i=0; i < MAX_NODES; i++)

{

tmp->next = malloc(sizeof(NODE));

if(!tmp->next) break;

tmp->next->data = i + 2;

tmp = tmp->next;

}

reverse_list(&head);

tmp = head;

while(tmp)

{

printf("%d\n", tmp->data);

tmp = tmp->next;

}

return 0;

}

-Neo
Nov 14 '05 #1
11 2794
Neo wrote:
Could U plz. suggest me how can i reverse a link list (without

recursion)???

assuming the original list is in old_list and the reversed list will be
created in new_list

WHILE old_list not empty
get item from head of old_list
add item to tail of new_list

--
Nick Keighley

Nov 14 '05 #2

"Nick Keighley" <ni******************@hotmail.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...
Neo wrote:
Could U plz. suggest me how can i reverse a link list (without

recursion)???

assuming the original list is in old_list and the reversed list will be
created in new_list

WHILE old_list not empty
get item from head of old_list
add item to tail of new_list


Ummmm...

Woundn't that give you exactly the same list?

I'd suggest:

WHILE old_list not empty
get item from head of old_list
add item to head of new_list

So the last item of old_list is the head of new_list.
Nov 14 '05 #3
On 4 Jan 2005 04:05:17 -0800, Nick Keighley
<ni******************@hotmail.com> wrote:
Neo wrote:
Could U plz. suggest me how can i reverse a link list (without

recursion)???

assuming the original list is in old_list and the reversed list will be
created in new_list

WHILE old_list not empty
get item from head of old_list
add item to tail of new_list


I think you mean "add item to head of new_list":

old list item new list
removed
12345 1 1
2345 2 21
345 3 321
45 4 4321
5 5 54321

(Assuming that the 'head' of a list is on the left.)

Chris C
Nov 14 '05 #4
Neo
"Nick Keighley" <ni******************@hotmail.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...
Neo wrote:
Could U plz. suggest me how can i reverse a link list (without

recursion)???

assuming the original list is in old_list and the reversed list will be
created in new_list

WHILE old_list not empty
get item from head of old_list
add item to tail of new_list

Nick Keighley


Well,

I've implemented it as follows, its working fine.
Is there any possibility to optimize reverse_list() further :
#include<stdio.h>
#include<stdlib.h>

#define MAX_NODES 8

typedef struct node {
int data;
struct node *next;
} NODE;

void reverse_list(NODE **head)
{
NODE *t;
NODE *newlist = NULL;

while(*head) {
t = *head; /*** Take out an element off the head ***/
*head = (*head)->next;

/*** Add it in front of newlist ***/
if(!newlist) {
t->next = 0;
newlist = t;
}
else {
t->next = newlist;
newlist = t;
}
}
*head = newlist;
}
int main()
{
NODE *head, *tmp;
int i;

head = malloc(sizeof(NODE));
if(!head) return 1;
head->data = 1;
head->next = NULL;
tmp = head;

for(i=0; i < MAX_NODES; i++)
{
tmp->next = malloc(sizeof(NODE));
if(!tmp->next) break;
tmp->next->data = i + 2;
tmp = tmp->next;
}
tmp->next = NULL;

reverse_list(&head);
tmp = head;
while(tmp)
{
printf("%d\n", tmp->data);
tmp = tmp->next;
}

return 0;
}

Nov 14 '05 #5
On Tue, 4 Jan 2005 19:10:12 +0530, "Neo" <ti***************@yahoo.com>
wrote:
....
/*** Add it in front of newlist ***/ if(!newlist) {
t->next = 0;
newlist = t;
}
else {
The if-else is superfluous. newlist contains a NULL so both branches of
the if are guaranteed to do the same thing.
t->next = newlist;
newlist = t;
}
}


--
#include <standard.disclaimer>
_
Kevin D Quitt USA 91387-4454 96.37% of all statistics are made up
Per the FCA, this address may not be added to any commercial mail list
Nov 14 '05 #6
Neo wrote:

Could U plz. suggest me how can i reverse a link list (without recursion)???


It's an easy thing to do. However we don't do homework, and we
also don't respond well to people who use kewl abreviations.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!

Nov 14 '05 #7
Neo

"Kevin D. Quitt" <KQ****@IEEInc.com> wrote in message
news:as********************************@4ax.com...
On Tue, 4 Jan 2005 19:10:12 +0530, "Neo" <ti***************@yahoo.com>
wrote:
...
/*** Add it in front of newlist ***/
if(!newlist) {
t->next = 0;
newlist = t;
}
else {


The if-else is superfluous. newlist contains a NULL so both branches of
the if are guaranteed to do the same thing.
t->next = newlist;
newlist = t;
}
}


Yeah! right.
Thanks Kevin!


--
#include <standard.disclaimer>
_
Kevin D Quitt USA 91387-4454 96.37% of all statistics are made up
Per the FCA, this address may not be added to any commercial mail list

Nov 14 '05 #8
Neo wrote:
Could U plz. suggest me how can i reverse a link list (without recursion)???


Although this wasn't your question, it's interesting to note that
reversing a doubly-linked list in-place is much easier. Simply swap the
prev and next pointers on each node:

struct node {
/* data */
struct node* next;
struct node* prev;
};

void reverse_dll(struct node* node) {
while(node != NULL) {
struct node* nextNode = node->next;
node->next = node->prev;
node->prev = nextNode;
node = nextNode;
}
}

--
Derrick Coetzee
I grant this newsgroup posting into the public domain. I disclaim all
express or implied warranty and all liability. I am not a professional.
Nov 14 '05 #9
Neo wrote:

"Nick Keighley" <ni******************@hotmail.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...
Neo wrote:
Could U plz. suggest me how can i reverse a link list (without

recursion)???

assuming the original list is in old_list and the reversed list will be
created in new_list

WHILE old_list not empty
get item from head of old_list
add item to tail of new_list

Nick Keighley


Well,

I've implemented it as follows, its working fine.
Is there any possibility to optimize reverse_list() further :

#include<stdio.h>
#include<stdlib.h>

#define MAX_NODES 8

typedef struct node {
int data;
struct node *next;
} NODE;

void reverse_list(NODE **head)
{
NODE *t;
NODE *newlist = NULL;

while(*head) {
t = *head; /*** Take out an element off the head ***/
*head = (*head)->next;

/*** Add it in front of newlist ***/
if(!newlist) {
t->next = 0;
newlist = t;
}
else {
t->next = newlist;
newlist = t;
}
}
*head = newlist;
}

int main()
{
NODE *head, *tmp;
int i;

head = malloc(sizeof(NODE));
if(!head) return 1;
head->data = 1;
head->next = NULL;
tmp = head;

for(i=0; i < MAX_NODES; i++)
{
tmp->next = malloc(sizeof(NODE));
if(!tmp->next) break;
tmp->next->data = i + 2;
tmp = tmp->next;
}
tmp->next = NULL;

reverse_list(&head);
tmp = head;
while(tmp)
{
printf("%d\n", tmp->data);
tmp = tmp->next;
}

return 0;
}


/* BEGIN new.c */

#include<stdio.h>
#include<stdlib.h>

#define MAX_NODES 8

typedef struct node {
int data;
struct node *next;
} NODE;
NODE *reverse_list(NODE *head)
{
NODE *previous, *next_node;

if (head != NULL) {
next_node = NULL;
while (head -> next != NULL) {
previous = head;
head = previous -> next;
previous -> next = next_node;
next_node = previous;
}
head -> next = next_node;
}
return head;
}
int main(void)
{
NODE *head, *tmp;
int i;

head = malloc(sizeof(NODE));
if (head == NULL) {
exit(EXIT_FAILURE);
}
head -> data = 1;
head -> next = NULL;
tmp = head;
for (i = 0; MAX_NODES > i; ++i) {
tmp -> next = malloc(sizeof *(tmp -> next));
if (tmp -> next == NULL) {
break;
}
tmp -> next -> data = i + 2;
tmp = tmp -> next;
}
tmp -> next = NULL;
head = reverse_list(head);
tmp = head;
while (tmp != NULL) {
printf("%d\n", tmp -> data);
tmp = tmp -> next;
}
free(head);
return 0;
}

/* END new.c */
Nov 14 '05 #10
pete wrote:
Neo wrote:
"Nick Keighley" <ni******************@hotmail.com> wrote
Neo wrote:

Could U plz. suggest me how can i reverse a link list (without
recursion)???

assuming the original list is in old_list and the reversed list will be
created in new_list

WHILE old_list not empty
get item from head of old_list
add item to tail of new_list
I've implemented it as follows, its working fine.
Is there any possibility to optimize reverse_list() further :

.... snip ...
/* BEGIN new.c */

#include<stdio.h>
#include<stdlib.h>

.... snip ...

Here is my version, and some more. This has been published here
before.

/* List handling, reversal, sort, merge, split */
/* file listops.h */
/* By C.B. Falconer. Public Domain, use as you wish */
/* Attribution appreciated. */
/* ================== 30 April, 2001 ================== */

#ifndef listops_h_
#define listops_h_

#include <stddef.h> /* NULL */
#include <iso646.h> /* not, and */

/* The bare minimum to form a linked list */
typedef struct node {
struct node *next;
void *data;
} node, *nodeptr;

/* ================================================== ===== */
/* believed necessary and sufficient for NULL terminations */
/* Reverse a singly linked list. Reentrant (pure) code */
nodeptr revlist(nodeptr root);

/* ================================================== ===== */
/* split list p into 2 nearly equal lists, return 2nd part */
nodeptr splitlist(nodeptr p);

/* ================================ */
/* Merge two ordered lists into one */
nodeptr mergelists(nodeptr p1, nodeptr p2,
int (*cmp)(void *, void*)); /* compare */

/* ================================================== */
/* Recursively sort a linked list. The sort is stable */
/* This is an O(NlogN) process for all lists. */
nodeptr mergesort(nodeptr root,
int (*cmp)(void *, void*)); /* compare */

#endif

/* end listops.h */

/* List handling, reversal, sort, merge, split */
/* file listops.c */
/* By C.B. Falconer. Public Domain, use as you wish */
/* Attribution appreciated. */
/* ================== 30 April, 2001 ================== */
/* using stdops.h, 16 Sept. 2001 */

#include "stdops.h" /* bool, true, false, not, and, or, xor */
#include "listops.h"

/* ================================================== ===== */
/* believed necessary and sufficient for NULL terminations */
/* Reverse a singly linked list. Reentrant (pure) code */
nodeptr revlist(nodeptr root)
{
nodeptr curr, nxt;

if (root) { /* non-empty list */
curr = root->next;
root->next = NULL; /* terminate new list */
while (curr) {
nxt = curr->next; /* save for walk */
curr->next = root; /* relink */
root = curr; /* save for next relink */
curr = nxt; /* walk onward */
}
}
/* else empty list is its own reverse; */
return root;
} /* revlist */

/* ================================================== ===== */
/* split list p into 2 nearly equal lists, return 2nd part */
nodeptr splitlist(nodeptr p)
{
nodeptr p1, p2, p3;

p1 = p2 = p3 = p;
if (not p) return NULL;
do {
p3 = p2;
p2 = p2->next; /* advance 1 */
p1 = p1->next;
if (p1) p1 = p1->next; /* advance 2 */
} while (p1);

/* now form new list after p2 */
p3->next = NULL; /* terminate 1st half */
return p2;
} /* splitlist */

/* ================================ */
/* Merge two ordered lists into one */
nodeptr mergelists(nodeptr p1, nodeptr p2,
int (*cmp)(void *, void*)) /* compare */
{
node n;
nodeptr p;

p = &n;
n.next = p;

while (p1 and p2) {
if (cmp(p1, p2) <= 0) {
p->next = p1; p = p1; p1 = p1->next;
}
else {
p->next = p2; p = p2; p2 = p2->next;
}
}
/* at least one list now empty, copy other */
/* one or both of these operations is null */
if (p1) p->next = p1;
if (p2) p->next = p2;

/* check for empty lists */
if (n.next == &n) return NULL;
return n.next;
} /* mergelists */

/* ================================================== */
/* Recursively sort a linked list. The sort is stable */
/* This is an O(NlogN) process for all lists. */
nodeptr mergesort(nodeptr root,
int (*cmp)(void *, void*)) /* compare */
{
nodeptr p;

if (root and root->next) { /* 2 up items in list */
p = splitlist(root); /* alters list root */
root = mergelists(mergesort(root, cmp),
mergesort( p, cmp),
cmp);
}
/* else the unit or empty list is already sorted */

return root;
} /* mergesort */

/* end listops.c */

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #11
pete wrote:
/* BEGIN new.c */

#include<stdio.h>
#include<stdlib.h>

#define MAX_NODES 8

typedef struct node {
int data;
struct node *next;
} NODE;

NODE *reverse_list(NODE *head)
{
NODE *previous, *next_node;

if (head != NULL) {
next_node = NULL;
while (head -> next != NULL) {
previous = head;
head = previous -> next;
previous -> next = next_node;
next_node = previous;
}
head -> next = next_node;
}
return head;
}

void list_free(NODE *node)
{
NODE *next_node;

while (node != NULL) {
next_node = node -> next;
free(node);
node = next_node;
}
}
int main(void)
{
NODE *head, *tmp;
int i;

head = malloc(sizeof(NODE));
if (head == NULL) {
exit(EXIT_FAILURE);
}
head -> data = 1;
head -> next = NULL;
tmp = head;
for (i = 0; MAX_NODES > i; ++i) {
tmp -> next = malloc(sizeof *(tmp -> next));
if (tmp -> next == NULL) {
break;
}
tmp -> next -> data = i + 2;
tmp = tmp -> next;
}
tmp -> next = NULL;
head = reverse_list(head);
tmp = head;
while (tmp != NULL) {
printf("%d\n", tmp -> data);
tmp = tmp -> next;
} free(head);
Change that to

list_free(head);
return 0;
}

/* END new.c */


--
pete
Nov 14 '05 #12

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

Similar topics

35
by: Raymond Hettinger | last post by:
Here is a discussion draft of a potential PEP. The ideas grew out of the discussion on pep-284. Comments are invited. Dart throwing is optional. Raymond Hettinger ...
59
by: Raymond Hettinger | last post by:
Please comment on the new PEP for reverse iteration methods. Basically, the idea looks like this: for i in xrange(10).iter_backwards(): # 9,8,7,6,5,4,3,2,1,0 <do something with i> The...
14
by: Raymond Hettinger | last post by:
Based on the feedback here on comp.lang.python, the pep has been updated: www.python.org/peps/pep-0322.html The key changes are: * reversed() is being preferred to ireverse() as the best...
3
by: engsolnom | last post by:
I need to use the built-in method 'reverse', but notice strange behavior. Foe example: print my_list.reverse() doesn't work. new_list = my_list.reverse() doesn't work. my_list.reverse()...
19
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.,...
11
by: Noah | last post by:
I have a list of tuples I want to reverse the order of the elements inside the tuples. I know I could do this long-form: q = y = for i in y: t=list(t)
41
by: rick | last post by:
Why can't Python have a reverse() function/method like Ruby? Python: x = 'a_string' # Reverse the string print x Ruby: x = 'a_string' # Reverse the string
4
by: sandra19 | last post by:
how could i reverse the word in a DAT file without using link and append the reverse text in the DAT file.? any suggestions? i already tried reversing it using linked list but i want to try another...
1
by: Chris Rebert | last post by:
On Thu, Oct 2, 2008 at 8:07 PM, David Di Biase <dave.dibiase@gmail.comwrote: Rather than defining a comparison function here (which is less efficient), you can use the 'key' argument, which...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
0
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...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.