Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
------------------------------------------------------Given
1->2->3->4->5->NULL
and k = 2
,return
4->5->1->2->3->NULL
.The key of this problem:
1. Search the linked list to get a length of the list.
2. How to attach a node and dis-attach a node. An important character for list is that it's easy to go forward along the list but difficult to go backward. An easy way to overcome this drawback is to connect the list as a circle and then we can treat the 'go back' as 'go ahead'.
Following is a complete codes for C++ project. You can copy and past into VC to run directly.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#include "stdafx.h"
#
include <cstdlib>
#include <iostream> // std::cout
#include <algorithm> // std::sort
#include <vector> // std::vector
#
include <map> // std::map
using namespace std;
//Definition
for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/////////////////////////////////////////////
//Rotate List
/////////////////////////////////////////////
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
ListNode* l_tmp;
l_tmp = head;
int count = 1;
if (k == 0 || head == NULL) return head;
//go to
the last node
while (head->next != NULL){ //Note: head==NULL means the struct is empty;
//head->next==NULL means the pointer in next is NULL
count++;
head = head->next;
}
//revise
the length of k
k = k%count;
//connect
as a circle
head->next = l_tmp;
//go
ahead again along the circle for count-k steps
for (int i = 1; i <= count - k; i++){
head = head->next;
}
//when
arrive at the position that is one before the target
//clear
the pointer and move head to next
l_tmp = head;
head = head->next;
l_tmp->next = NULL;
return head;
}
};
int main(int argc, char *argv[])
{
ListNode* l1; //define a pointer
that points to struct
l1 = new ListNode(1);//assign a value to the
pointer
l1->next = new ListNode(2);//assign a value to the next linked pointer
int k = 1;
Solution s;
ListNode* result;
result = s.rotateRight(l1, k);
cout << "the solution is";
cout << result->val;
cout << "\n";
cout << "HELLO:\n";
cout << "\n";
cout << " Hello,
world!\n";
int age;
cin >> age;
return 0;
}
No comments:
Post a Comment