Cover image for Classic Interview 150 Questions P61 Rotate List

Classic Interview 150 Questions P61 Rotate List


Timeline

Timeline

2025-11-21

init

linked list

Problem:

Split the linked list into two groups, then attach the tail of the latter group to the front group.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
struct ListNode {	int val;	ListNode *next;	ListNode()		: val(0)		, next(nullptr)	{	}	ListNode(int x)		: val(x)		, next(nullptr)	{	}	ListNode(int x, ListNode *next)		: val(x)		, next(next)	{	}};class Solution {    public:	ListNode *rotateRight(ListNode *head, int k)	{		int nr_node = 0;		ListNode *p = head, *new_head_prev, *new_head, *tail;		while (p != nullptr) {			if (p->next == nullptr) {				tail = p;			}			p = p->next;			nr_node++;		}		if (nr_node == 0) { // in case divided by zero			return head;		}		k = k % nr_node;		if (k == 0) { // head == nullptr || k==0			return head;		}		new_head_prev = head;		for (int i = 0; i < nr_node - k - 1; i++) {			new_head_prev = new_head_prev->next;		}		new_head = new_head_prev->next;		tail->next = head;		new_head_prev->next = nullptr;		return new_head;	}};
Loading comments…