Single-chain table algorithm question

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.