Simple solutions for complex problems on single linked list..

This is an article on Simple solutions for complex problems on single linked list.. in C.

Listed here are few common complex operations of single linked list that is to be needed by certain applications. These operations should be done in single traversal for improved performance.

Here are few of them and their solutions..

1. Reverse the list.
2. Find n-th node from tail end.
3. Find middle node of the list.
4. Delete a node whose address is known, without having the head node's address.

1. Reverse the list
Logic :

a. Get each node from front end till last.
b. Add them into another list at front.

2. Find n-th node from tail end.

a. Have two pointers pointer1 and pointer2.
b. Point all of them to head initilally.
c. Move only pointer1 for n nodes.
d. Move both pointers for the rest nodes of list.
e. At the end of traversal, pointer2 will be pointing to n-th node from tail.

3. Find middle node of the list.

a. Have two pointers pointer1 and pointer2.
b. Point all of them to head initilally.
c. Move only pointer1 by one node.
d. Move pointer2 by two nodes till the end of list.
e. At the end of traversal, pointer1 will be pointing to middle node from tail.

4. Delete a node without having the head node's address

a. copy the contents of next node's data to current node's data.
b.Store the next node's next node at current node's link.

In all cases, we have to take care of boundary conditions as well as memory leaks.
Here is the code..

one more question
how to reverse block in singly linked list
like
1->2->3->4->5->6->7->8->9->10->11->12
let us take block size as 3
so reversed list should be like this
3->2->1->6->5->4->9->8->7->12->11->10