C/C++ Algorithms: 1. Reverse A Singly Linked List
C/C++ Algorithms: 1. Reverse A Singly Linked List
//
// iterative version
//
Node* ReverseList( Node ** List )
{
while ( temp1 )
{
*List = temp1; //set the head to last node
return *List;
}
Page 1 of 7
C/C++ algorithms
3. Sort a linked list
//sorting in descending order
struct node
{
int value;
node* NEXT;
}
//Assume HEAD pointer denotes the first element in the //linked
list
// only change the values…don’t have to change the //pointers
first=first->NEXT;
}
}
4. Reverse a string
void ReverseString (char *String)
{
char *Begin = String;
char *End = String + strlen(String) - 1;
char TempChar = '\0';
Page 2 of 7
C/C++ algorithms
5. Insert a node a sorted linked list
void sortedInsert(Node * head, Node* newNode)
{
Node *current = head;
// traverse the list until you find item bigger the // new
node value
//
while (current!= NULL && current->data < newNode->data)
{
current = current->next);
}
//
// insert the new node before the big item
//
newNode->next = current->next;
current = newNode;
}
Page 3 of 7
C/C++ algorithms
8. Write a function that takes in a string parameter
and checks to see whether or not it is an integer,
and if it is then return the integer value.
#include <stdio.h>
if( flag == 1 )
return atoi(s);
else
return 0;
}
main()
{
printf("%d",strtoint("0123"));
printf("\n%d",strtoint("0123ii"));
}
PrintTree(node->left );
Printf(“%d”, node->data);
PrintTree(node->right );
}
Page 4 of 7
C/C++ algorithms
10. print integer using only putchar
//
// recursive version
//
void PrintNum ( int Num )
{
if ( Num == 0 )
return;
PrintNum ( Num / 10 );
Puthcar ( ‘0’+ Num % 10 );
}
If ( num > 0 )
return Num * Factorial ( Num –1 );
else
return 1;
}
//
// iterative version
//
return result;
}
Page 5 of 7
C/C++ algorithms
12. Generate Fib numbers:
int fib( n ) // recursive version
{
if ( n < 2 )
return 1;
else
return fib ( n –1 ) + fib ( n –2 );
if ( n < 2 )
return 1;
for ( i = 1; i < N; i++)
{
f = f1 + f2;
f1= f2;
f = f1;
}
return f;
}
return pStr;
}
Page 6 of 7
C/C++ algorithms
14. Return Nth the node from the end of the linked
list in one pass.
Node * GetNthNode ( Node* Head , int NthNode )
{
Node * pNthNode = NULL;
Node * pTempNode = NULL;
int nCurrentElement = 0;
First version:
Optimized version:
Page 7 of 7