Nov 8, 2009

Data Structures -- Linked List -- Reverse - Reverse a linked list

free web hosting
Open Discussion > MODERATED AREA > Computers > Programming Languages > Others

Data Structures -- Linked List -- Reverse - Reverse a linked list

varalu
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 my friend. But i guess we still have some problems in the above code and can be refined more.
Do post back with better ideas and solutions.

 

 

 


Comment/Reply (w/o sign-up)

pointybirds
There aren't too many simpler iterative algorithms than the one you've given. I would perhaps have the function return a result:

CODE
Node *reverse(Node *head) {
   Node *curr=head, *prev=NULL, *next;

   while (curr != NULL) {
      next = curr->next;
      curr->next = prev;
      prev = curr;
      curr = next;
   }
   return prev;
}

Comment/Reply (w/o sign-up)

FeedBacker
i think this will serve better
Data Structures -- Linked List -- Reverse

Replying to pointybirds

NODE* revlist(NODE *head)
{
NODE *tmp=NULL, *tmp1=NULL;
while (head != NULL)
{
tmp = head;
head = head->next;
tmp->next = tmp1;
tmp1 = tmp;
}
return head;
}


-reply by raja

Comment/Reply (w/o sign-up)

FeedBacker
Replying to Trap FeedBackerYou are returning NULL, set head to tmp first.

Comment/Reply (w/o sign-up)

iGuest-prangya
1.Give an example in which there is the implimentation of copy constructor and assignment operator an string should be there.

2. Why static method don't have this pointer?

-question by prangya

Comment/Reply (w/o sign-up)

iGuest-jagannath
simple linked list
Data Structures -- Linked List -- Reverse

/*
* Simple operations on linked list. If any problem
* please mail to me jagannath_pattar@yahoo.Co.In
*/

#include <stdio.H>

/*
* Data structure used, its simple :)
*/
Typedef struct linked_list_s
{
int value;
struct linked_list_s *next;
}linked_list_t;

/*
* Add a node at the end of the list.
*/
Linked_list_t* add_node(linked_list_t *head, int value)
{
linked_list_t *newNode = NULL;
linked_list_t *node = head;
linked_list_t *prev = head;

newNode = (linked_list_t *)calloc(1, sizeof(linked_list_t));
newNode->value = value;

while(node)
{
prev = node;
node = node->next;
}
if(prev == node)
return newNode;

prev->next = newNode;

return head;
}

/*
* delete a specified node from the list.
*/
Linked_list_t* delete_node(linked_list_t *head, int value)
{
linked_list_t *node = NULL;
linked_list_t *prev = NULL;

for(node = head; node != NULL; prev = node, node = node->next)
{
if(node->value == value)
{
//Check for head node modification
if(prev == NULL)
{
head = head->next;
free(node);
return head;
}

prev->next = node->next;
free(node);
return head;
}
}
return head;
}

/*
* display all the nodes of the list.
*/
Void list_nodes(linked_list_t *head)
{
linked_list_t *node = head;
printf("\nHead");
while(node)
{
printf("->%d ",node->value);
node = node->next;
}
printf("->NULL\and");
}


/*
* Display all the nodes in reverse order withoout modifying list.
*/
Void list_nodes_in_reverse_order(linked_list_t *head)
{
linked_list_t *end = NULL;
linked_list_t *node = NULL;

printf("\nReverse Head");
while(head != end)
{
node = head;
while(node->next != end)
node = node->next;

printf("->%d ",node->value);
end = node;
}
printf("->NULL\and");
}


/*
* Reversing the linked list with recursion; I recommond this method..
*/
Linked_list_t* reverse_with_recursion_anotherway(linked_list_t* current, linked_list_t* parent)
{
linked_list_t* revhead = NULL;

if(current == NULL)
revhead = parent;
else
{
revhead = reverse_with_recursion_anotherway(current->next, current);
current->next = parent;
}
return revhead;
}

/*
* Reversing the linked list;
*/
Linked_list_t* reverse_with_recursion(linked_list_t* node)
{
linked_list_t* temp = NULL;

if(node->next == NULL)
return node;

temp = reverse_with_recursion(node->next);
temp->next =node;
return node;
}

/*
* reversing linked list without recursion.
*/
Linked_list_t* reverse_without_recursion(linked_list_t* head)
{
linked_list_t* prevNode = NULL;
linked_list_t* currNode = head;
linked_list_t* nextNode = head->next;

while(currNode)
{
currNode->next = prevNode;
prevNode = currNode;
if(nextNode == NULL)
break;
currNode = nextNode;
nextNode = nextNode->next;
}
return currNode;
}

/*
* main program, which displays menu for maitaining linked list.
*/
Main()
{
int choice = -1;
int value = 0;
linked_list_t *head = NULL;
linked_list_t *node = NULL;

do
{
printf("\and what you wanna do?\and");
printf("1. Add a node \and");
printf("2. Delete a node \and");
printf("3. List all nodes \and");
printf("4. Reverse (without recursion) the list \and");
printf("5. Reverse (recursively) the list \and");
printf("6. Reverse (recursively) another way\and");
printf("7. Just display in reverse order\and");
printf("8. Exit \and");
scanf("%d",&choice);

switch(choice)
{
case 1:
printf("\nEnter value: ");
scanf("%d",&value);
head = add_node(head, value);
break;

case 2:
printf("\nEnter value: ");
scanf("%d",&value);
head = delete_node(head, value);
break;

case 3:
list_nodes(head);
break;

case 4:
node = head;
head = reverse_without_recursion(head);
break;

case 5:
node = head;
while(node->next)
node = node->next;
head = reverse_with_recursion(head);
head->next = NULL;
head = node;
break;

case 6:
head = reverse_with_recursion_anotherway(head, NULL);
break;

case 7:
list_nodes_in_reverse_order(head);
break;

case 8:
exit(0);
break;
}
}while(1);
}


-reply by jagannath

 

 

 


Comment/Reply (w/o sign-up)

(G)Bamo
Linear Linked Lists
Data Structures -- Linked List -- Reverse

How to reverse a linear linked list without using a temporaly variable.

-question by Bamo


Comment/Reply (w/o sign-up)

(G)Bamo
Singly Linked Linear List(SLLL) and Doubly Linked Linear List(DLLL)
Data Structures -- Linked List -- Reverse

Write an Algorithm to reverse a SLLL and DLLL.

-question by Bamo

Comment/Reply (w/o sign-up)

(G)michael
linked list reverse and memory
Data Structures -- Linked List -- Reverse

in the some of your funntions when returning the memory becomes null

head->value=ok

head->next   becomes null after function exit

==============

void ReverseList(LISTP* head)

{

LISTP *temp,*current,*result;

temp=NULL;

result=NULL;

current=head;

while(current!=NULL)

{

temp=current->next;

current->next=result;

result=current;

current=temp;

}

head=result;

}

===================

 

if I print hte list inside the function it is ok

void display_list(LISTP* listp)

{

LISTP* temp=listp;

while(temp->next!=NULL)

{

printf("%d\and",temp->data);

temp=temp->next;

}

}

======================

 

but if I exit the function the next pointer becomes null , I suppoise the solution is using static pointer allocated outside the function ... 

any way my idea

==========

void reverselist(LISTP* listp)

{

LISTP* next = (LISTP*)malloc(sizeof(LISTP));

LISTP* next_of_next = (LISTP*)malloc(sizeof(LISTP));

next=listp->next;

if(next!=NULL)

next_of_next = next->next;

listp->next = NULL;

while(next_of_next!=NULL)

{

next->next=listp;

listp=next;

next=next_of_next;

next_of_next=next_of_next->next;

}

 

display_list(listp);

//free(next);    ???  is nneeded

//free(next_of_next);  is needed

}

-reply by michael


Keywords: reverse linked list

Comment/Reply (w/o sign-up)

(G)mharie_chue
stack codes
Data Structures -- Linked List -- Reverse

hi there guys...Can you help me in my simple problem?

how was the codes in reversing a name using stacks?

just like this...M a r I c h u

then the output will be like this one...U h c I r a m

thanks for your help.,in advance!

-question by mharie_chue

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)

Similar Topics

Keywords : data, structures, linked, list, reverse, reverse, 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 -- 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....
  10. Data Structures -- Linked List
    Find the nth last element in linked list. (14)
    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") po....
  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, reverse, reverse, linked, list

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


Data Structures -- Linked List -- Reverse - Reverse a linked list

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