Java教程

408 数据结构算法题2019

本文主要是介绍408 数据结构算法题2019,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
#include<iostream>
using namespace std;
struct node {
    int data;
    struct node* next;
};

node* solustion(node* head) {
    node* fast = head, * slow = head;

    while ( fast != NULL&& fast->next != NULL) {
        if (fast == head) {
            fast = head->next;
            slow = head;
        }
        else {
            fast = fast->next->next;
            slow = slow->next;
        }
    }
    
    node* pre = slow, * nextSlow = slow->next->next;
    slow = slow->next;
    pre->next = NULL;
    while(nextSlow!=NULL){
        slow->next = pre;
        pre = slow;
        slow = nextSlow;
        nextSlow = nextSlow->next;
    }
    slow->next = pre;
    cout << slow->data << endl;
    node* tempHead = head, * tempTail = slow;
    node* nextTempHead = tempHead->next, * nextTempTail = slow->next;
    while (tempHead!=NULL) {
        tempHead->next = tempTail;
        tempTail->next = nextTempHead;

        tempHead = nextTempHead;
        tempTail = nextTempTail;
        if (tempHead != NULL && tempTail != NULL)
        {
            nextTempHead = nextTempHead->next;
            nextTempTail = nextTempTail->next;
        }
    }
    while (head != NULL) {
        cout << head->data << "  ";
        head = head->next;
    }
    return head;

}
int main() {

    int in = 0;
    node* head = NULL;
    node* tempHead = NULL, * temp = NULL;
    while (cin >> in) {
        if (head == NULL) {
            head = (node*)malloc(sizeof(node));
            head->next = NULL;
            head->data = in;
            
            tempHead = head;
        }
        else {
            temp = (node*)malloc(sizeof(node));
            temp->next = NULL;
            temp->data = in;
            tempHead->next = temp;
            tempHead = temp;
        }
    }
    solustion(head);
}

在解此题的时候让我对于while或者说所有的循环有了新的理解。

这篇关于408 数据结构算法题2019的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!