#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或者说所有的循环有了新的理解。