Write c program to print linked list in reverse order. This very simple linked list interview questions for the beginners. you have to reverse the sequence only. So it is different problem compare to reversing linked list.

c program to print linked list in reverse orderc,python program to print linked list in reverse order

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

// data structure for link list
typedef struct list {
	int data; //data
	struct list *next; // point to next list
} list;

list* make_node(int data);
list* insert(list* head, int data);
void print_rev_ord(list *head) {
	if (head == NULL)
		return;
	print_rev_ord(head->next);
	printf("%d ", head->data);
}

int main() {
	list *head = NULL;
	// insert 2 5 4 8 9
	head = insert(head, 2);
	insert(head, 5);
	insert(head, 4);
	insert(head, 8);
	insert(head, 9);
	// call print_rev_ord function
	// it should print 9 8 4 5 2
	print_rev_ord(head);
	printf("\n");
	return 0;
}

list* insert(list* head, int data) {
	// create first node
	if (head == NULL)
		return make_node(data);
	else {
		// go to last node
		list *p = head;
		while (p->next != NULL)
			p = p->next;

		// create new node
		list *new_one = make_node(data);
		p->next = new_one;
		return new_one;
	}
}

list* make_node(int data) {
	list* ll = (list*) malloc(sizeof(list));
	ll->data = data;
	ll->next = NULL;
}
#python program to print link
#list in reverse order

#data structure for node

class Node:
    def __init__(self,data):
        self.data = data
        self.next = None;

    def get_next(self):
        return self.next;

    def set_next(self,new_node):
        self.next = new_node;

class LinkList:
    def __init__(self):
        self.head = None;

    def isEmpty(self):
        return slef.head == None;

    def append(self,data):
        new_node = Node(data)
        if self.head == None:
            self.head = new_node
            return

        curr = self.head
        while curr.next:
            curr = curr.next

        curr.next = new_node

    def printli(self):
        curr = self.head
        print "the list is:"
        while curr:
            print (curr.data),
            curr = curr.next


    def print_reverse(self,item):
        if (item == None):
            return
        self.print_reverse(item.get_next())
        print item.data,

if __name__=='__main__':
    ll=LinkList()
    ll.append(2)
    ll.append(5)
    ll.append(4)
    ll.append(8)
    ll.append(9)
    #ptint list
    ll.printli()
    print "\nthe list is in reverse order:\n"
    ll.print_reverse(ll.head)

How it works

print linked list in reverse order




Related Contents to follow