Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct node{
- int n;
- struct node *next;
- } Node;
- Node *init_node(int n){
- Node *tmp = (Node *) malloc(sizeof(Node));
- tmp->n = n;
- tmp->next = NULL;
- return tmp;
- }
- Node *remove_nth_node(Node *cur_ptr, int n, int len){
- Node *tmp = cur_ptr;
- Node *node_to_free;
- if (n == 1)
- for (int i = 0; i < len-1; i++)
- tmp = tmp->next;
- else
- for (int i = 0; i < n-2; i++)
- tmp = tmp->next;
- node_to_free = tmp->next;
- tmp->next = tmp->next->next;
- free(node_to_free);
- return tmp->next;
- }
- int main(){
- int n, k;
- Node *head, *tmp_ptr;
- scanf("%d %d", &n, &k);
- head = init_node(1);
- tmp_ptr = head;
- for (int i = 1; i < n; i++){
- tmp_ptr->next = init_node(i+1);
- tmp_ptr = tmp_ptr->next;
- }
- tmp_ptr->next = head;
- tmp_ptr = head;
- if (tmp_ptr == NULL) exit(EXIT_FAILURE);
- while (tmp_ptr ->next != tmp_ptr){
- tmp_ptr = remove_nth_node(tmp_ptr, k, n);
- n--;
- }
- printf("%d",tmp_ptr->n);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement