Sunday, February 20, 2011

WAP to Delete A kth Node fromThe End in Linked List

#include
#include

/* Link list node */
struct node
{
int data;
struct node* next;
};

/* Function to get the nth node from the last of a linked list*/
void printNthFromLast(struct node *head, int n)
{
struct node *main_ptr = head;
struct node *ref_ptr = head;
struct node *prev=NULL;
struct node *temp=NULL;

int count = 0;
if(head != NULL)
{
while( count < n )
{
if(ref_ptr == NULL)
{
printf("%d is greater than the no. of "
"nodes in list", n);
return;
}
ref_ptr = ref_ptr->next;
count++;
} /* End of while*/

while(ref_ptr != NULL)
{ prev=main_ptr;
main_ptr = main_ptr->next;
ref_ptr = ref_ptr->next;
}
temp=main_ptr;
prev->next=temp->next;
//main_ptr=head;
printf("Node no. %d from last is %d ",
n, temp->data);

free(temp);
}
}

void push(struct node** head_ref, int new_data)
{
/* allocate node */
struct node* new_node =
(struct node*) malloc(sizeof(struct node));

/* put in the data */
new_node->data = new_data;

/* link the old list off the new node */
new_node->next = (*head_ref);

/* move the head to point to the new node */
(*head_ref) = new_node;
}

void print(struct node *current)
{
while(current!=NULL)
{
printf(" %d --> ", current->data);
current=current->next;

}

}
/* Drier program to test above function*/
int main()
{
/* Start with the empty list */
struct node* head = NULL;
push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 5);
push(&head, 20);

printNthFromLast(head, 3);

print(head);

getchar();
}

No comments :