A single-chain table is very simple, so pay attention to some details.
More hands-on lab paper.
#include <iostream>using namespace std;struct node { int key;node * next;node () :key(-1), next(NULL) {}node (int n) :key(n), next(NULL) {}};void print (node * head) {while (head) {cout << head->key << " ";head = head->next;}cout << endl;}node * reverse (node * head) { if (head == NULL ||head-> next == NULL) { return head;}node * pre = NULL;node * cur = head;node * next = NULL;while (cur) {next = cur->next;cur->next = pre;pre = cur;cur = next;}return pre;}node * reverse (node * head, int k) { if (head == NULL ||head-> next == NULL) { return head;}node * pre = NULL;node * cur = head;node * next = NULL;int i = 0;while (cur && i<k) {next = cur->next;cur->next = pre;pre = cur;cur = next;i++;}if (cur == NULL) {return pre;}node * new_head = pre;pre = NULL;while (cur) {next = cur->next;cur->next = pre;pre = cur;cur = next;}head->next = pre;return new_head;}node* pair_swap (node * head) { if (head == NULL ||head-> next == NULL) { return head;}node tmp_head;node* pre = &tmp_head;node* first = head;while (first && first->next) {node* second = first->next;first->next = second->next;second->next = first;pre->next = second;pre = first;first = first->next;}return tmp_head.next;}int main () {int key;node * head = NULL;while (cin >> key) {node * cur = new node(key);cur->next = head;head = cur;}print (head);head = reverse(head);print (head);head = reverse(head, 3);print (head);head = pair_swap(head);print (head);}
Sample input:
8 7 6 5 4 3 2 1
Sample output:
1 2 3 4 5 6 7 8 // original linked list
8 7 6 5 4 3 2 1 // flip the linked list
6 7 8 1 2 3 4 5 // flip the first K and flip the back
7 6 1 8 3 2 5 4 // Interaction Between Adjacent Elements
Single-chain table algorithm question