Showing posts with label reverse. Show all posts
Showing posts with label reverse. Show all posts

Sunday, October 14, 2012

Reverse a Linked List


#include<stdio.h>

typedef struct node{
int d;
struct node *next;
}Node;

Node* newNode(int data){
Node *n = (Node *)malloc(sizeof(Node));
n->d = data;
n->next = NULL;
return n;
}

void insert(struct node **headRef, int data){
Node *head = *headRef;
Node *temp;
if(head == NULL){
head = newNode(data);
} else {
temp = newNode(data);
temp->next = head;
head = temp;
}
*headRef = head;
}

void displayList(Node *head){
while(head != NULL){
printf("%d ",head->d);
head = head->next;
}
}

void reverseList(Node **headRef){
Node *head = *headRef;
Node *prev = NULL;
Node *temp;
if(head == NULL){
return;
}
while(head->next != NULL){
temp = head->next;
head->next = prev;
prev = head;
head = temp;
}
head->next = prev;
*headRef = head;
}

int main(){
Node *head = NULL;
int i;
for(i=10;i>0;i--){
insert(&head,i);
}
displayList(head);
reverseList(&head);
printf("\nafter reversing\n");
displayList(head);
return 0;
}

Sunday, August 12, 2012

Reverse a stack in place (without extra memory)



// You are given access to functions push, pop and isempty
void reverse(stack s){
        if(!isempty(s)){
                int temp = pop(s);
                reverse(s);
                pushtobottom(s,temp);
        }
}
 
pushtobottom(stack s, int data){
        if(!isempty(s)){
                temp = pop(s);
                pushtobottom(s,data);
                push(s,temp);
        } else {
                push(s,data);
        }
}