Implementation of C language data structure rotation linked list
- 2020-05-27 06:41:40
- OfStack
Implementation of C language data structure rotation linked list
Example:
Give me the list 1- > 2- > 3- > 4- > 5- > null and k = 2
Return to the 4 - > 5- > 1- > 2- > 3- > null
Analysis:
It feels intuitive, just find the segmentation point, remember that k may be larger than len, you need to take the module
Code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param head: the list
* @param k: rotate to the right k places
* @return: the list after rotation
*/
ListNode *rotateRight(ListNode *head, int k) {
// write your code here
if(head==NULL)
return head;
int len = 0;
ListNode*temp = head;
while(temp)
{
len++;
temp = temp->next;
}
k%=len;
if(k==0)
return head;
k = len-k;
temp = head;
while(k>1)
{
temp = temp->next;
k--;
}
ListNode*newStart = temp->next;
temp->next = NULL;
temp = newStart;
while(temp->next)
temp = temp->next;
temp->next = head;
return newStart;
}
};
The above is the implementation of C language data structure linked list, if you have any questions, please leave a message or to the community of this site to exchange discussion, this site on the data structure of the article there are many, I hope you search and consult, we make progress together!