链表的循环右移
#include<iostream>
using namespace std;
typedef struct ListNode {
int val;
ListNode* next;
ListNode():val(0),next(nullptr){}
ListNode(int x):val(x),next(nullptr){}
}ListNode,*LinkList;
LinkList TailInsert(int n) {
ListNode* head = new ListNode;
ListNode* r = head;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
ListNode* p = new ListNode(x);
r->next = p;
r = p;
}
r->next = nullptr;
return head;
}
//1 2 3 4 5 2 % 5
// 0 1 2 4 % 3 = 1
void movek(LinkList L,int k) {
ListNode* p = L->next;
ListNode* pre = L;
ListNode* r = p;
int n = 0;
while (r->next != nullptr) { //找到倒数第一个结点
r = r->next;
n++;
}
n++;
k = k % n;
if (k == 0) {
return;
}
ListNode* q = p;
while (q && k) {
if (q != nullptr) q = q->next;
k--;
}
if (k != 0) {
return;
}
while (q) {
pre = p;
p = p->next;
q = q->next;
}
//p就是倒数第k个结点
r->next = L->next;
L->next = p;
pre->next = nullptr;
}
void print(LinkList L) {
ListNode* p = L->next;
while (p) {
cout << p->val;
if (p->next != nullptr) cout << " ";
p = p->next;
}
cout << endl;
}
int main() {
int n;
while (cin >> n && n != 0) {
LinkList L = TailInsert(n);
int k; cin >> k;
movek(L,k);
print(L);
}
return 0;
}