Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h> // include everything
- using namespace std;
- /*
- STAFF'S FUNCTIONS
- */
- struct Node {
- int val;
- Node *next;
- };
- int get_list_size(Node* head) {
- return head == NULL ? 0 : 1 + get_list_size(head->next);
- }
- void print_list(Node* head) {
- if (head == NULL)
- return;
- printf("%d ", head->val);
- print_list(head->next);
- }
- Node* insert_front(Node* head, int val) {
- Node* new_node = new Node; // same as malloc(sizeof(Node))
- new_node->val = val;
- new_node->next = head;
- return new_node;
- }
- Node* free_list(Node* head) {
- if (head != NULL) {
- free_list(head->next);
- delete head; // same as free(head)
- }
- return NULL;
- }
- /*
- STUDENT'S FUNCTIONS
- */
- Node* get_tail(Node* head) {
- // your code here
- if(head -> next == nullptr) return head;
- head = get_tail(head -> next);
- return head;
- }
- Node* split_at_k(Node* head, int k) {
- // your code here
- if(k == 1){
- Node *cur = head -> next;
- head -> next = nullptr;
- return cur;
- }
- head = split_at_k(head -> next, k-1);
- return head;
- }
- Node* flip_chunks_of_two(Node* head) {
- // your code here
- if(head == nullptr) return nullptr;
- if(head -> next == nullptr) return head;
- Node *a, *b, *c;
- a = head;
- b = head -> next;
- c = head -> next -> next;
- b -> next = a;
- a -> next = flip_chunks_of_two(c);
- return b;
- }
- /*
- STAFF'S MAIN
- */
- void print_list_addresses(Node* head) {
- if (head == NULL)
- return;
- printf("%p ", head);
- print_list_addresses(head->next);
- }
- void print_list(Node* head, const char* name) {
- printf("%s\n", name);
- print_list(head);
- printf("\n");
- print_list_addresses(head);
- printf("\n");
- }
- int main()
- {
- // build input list
- int n, q;
- scanf("%d%d", &n, &q);
- int input[n];
- for (int i = 0; i < n; ++i)
- scanf("%d", &input[i]);
- Node* head = NULL;
- for (int i = n-1; i >= 0; --i)
- head = insert_front(head, input[i]);
- print_list(head, "Before: Input");
- if (q == 1) {
- Node* tail = get_tail(head);
- print_list(tail, "After: Tail node");
- } else if (q == 2) {
- int k; scanf("%d", &k);
- Node* sec2 = split_at_k(head, k);
- print_list(head, "After: Front list");
- print_list(sec2, "After: Back list");
- } else if (q == 3) {
- Node* newhead = flip_chunks_of_two(head);
- print_list(newhead, "After: Flipped pairs");
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement