Saturday, June 19, 2021
Home coding Write a program to reverse a linkedlist in given size.

Write a program to reverse a linkedlist in given size.

Given a linkedlist ,we have to make program to reverse node of a linkedlist of a given size.

Example:

Input:1 2 3 4 5 6  k=2
Output:2 1 4 3 6 5

Logic:

STEP 1:start traversing a node of linkedlist till reach end.
STEP 2:reverse a linked list and maintain a size k.
STEP 3:when we reach k .then reverse it and again start traversing again.

Code

Node * reverseKlinkedlist(Node *head, int k) 
{ 
    int length=0;
	Node* cur = head; 
	Node* nxt = NULL; 
	Node* prev = NULL; 
while (cur != NULL && length < k) 
	{ 
		nxt = cur->nxt; 
		cur->nxt = prev; 
		prev = cur; 
		cur= nxt; 
		length++; 
	}
	if (nxt != NULL) 
	{
	head->nxt = reverse(nxt, k); 
	}
	return prev; 
}

Ouput:

1 2 3 4 5 6 k=2
output:

2 1 4 3 6 5

Time Complexity:O(N)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments