链表 循环右移
作者:
晨灼灼
,
2021-03-07 21:22:51
,
所有人可见
,
阅读 439
#include<bits/stdc++.h>
using namespace std;
struct Node{
int val;
Node *next;
}head;
void build(){
int temp;
Node *p = &head;
while(cin>>temp && temp!=-1){
Node *now = (Node *)malloc(sizeof(Node));
now->val = temp;
p->next = now;
p = now;
p->next = NULL;
}
}
void print(){
Node *p = &head;
while(p->next != NULL){
cout<<p->next->val<<' ';
p = p->next;
}
cout<<endl;
}
void insert(int pos, int val){
Node *p = &head;
int cnt = 1;
while(p->next!=NULL && cnt < pos){
cnt ++;
p = p->next;
}
Node *now = (Node *)malloc(sizeof(Node));
now->val = val;
now->next = p->next;
p->next = now;
}
int get_len(){
Node *p = &head;
int cnt = 0;
while(p -> next != NULL){
cnt ++;
p = p->next;
}
return cnt;
}
void shift(int k){
Node *p = &head;
int len = get_len();
k %= len;
if(k == 0) return;
Node *ori_front = head.next;
int cnt = 0;
while(p->next != NULL && cnt < len - k){
p=p->next;
cnt ++;
}
Node *new_end = p;
p=p->next;
Node *new_front = p;
while(p->next != NULL){
p = p->next;
}
Node *ori_end = p;
// pointer assignment
head.next = new_front;
ori_end->next = ori_front;
new_end->next = NULL;
}
int main(){
build();
print();
cout<<get_len()<<endl;
shift(4);
print();
return 0;
}