This is a very popular interview question, which most people go wrong.The ideal solution to this problem is to keep the linked list sorted as you build it. Another question on this website teaches you how to insert elements into a linked list in the sorted order. This really saves a lot of time which would have been required to sort it.
However, you need to Get That Job....
Method1 (Usual method)
The general idea is to decide upon a sorting algorithm (say bubble sort). Then, one needs to come up with different scenariosto swap two nodes in the linked list when they are not in the required order. The different scenarios would be something like
1. When the nodes being compared are not adjacent and one of them is the first node.
2. When the nodes being compared are not adjacent and none of them is the first node
3. When the nodes being compared are adjacent and one of them is the first node.
4. When the nodes being compared are adjacent and none of them is the first node.
example bubble sort for a linked list goes like this (working C code!)...
#include
|
Monday, November 1, 2010
Data Structures Part 3
How do you sort a linked list? Write a C program to sort a linked list.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment