当前位置: 代码迷 >> 综合 >> 【leetcode】【单链表】【143】Reorder List
  详细解决方案

【leetcode】【单链表】【143】Reorder List

热度:13   发布时间:2023-12-21 18:06:27.0
#include<iostream>
using namespace std;struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}
};class Solution {
public://翻转链表ListNode* reverseList(ListNode* head) {ListNode* cur = head;ListNode* new_head = NULL;while (cur){ListNode* temp = cur;cur = cur->next;temp->next = new_head;new_head = temp;}head = new_head;return head;}void reorderList(ListNode* head) {if (head == NULL || head->next == NULL)return;ListNode* slow = head;ListNode* fast = head;ListNode* last = head;//得到list的中点while (fast&&fast->next){last = slow;slow = slow->next;fast = fast->next->next;}last->next = NULL;last = NULL;//后半段反转slow=reverseList(slow);fast = head;ListNode* temp = NULL;while (fast){temp = slow;slow = slow->next;temp->next = fast->next;fast->next = temp;last = fast->next;fast = fast->next->next;}if (slow)last->next = slow;}ListNode* createList(ListNode* head){int numOfNode;int value;cout << "please input number of listNode:";cin >> numOfNode;cin >> value;head = new ListNode(value);ListNode* cur = head;for (int i = 1; i < numOfNode; ++i){cin >> value;ListNode* temp = new ListNode(value);cur->next = temp;cur = temp;}return head;}void printNode(ListNode* head){ListNode* cur = head;while (cur){cout << cur->val << " ";cur = cur->next;}cout << endl;}
};int main(){ListNode* head = NULL;Solution lst;head = lst.createList(head);lst.printNode(head);lst.reorderList(head);lst.printNode(head);system("pause");return 0;
}

  相关解决方案