今天在leetcode上看到一个很有趣的题目,用O(nlogn)的时间对链表进行排序,思考一下,觉得最好的方法也就是归并排序了,其他排序都会对next指针有很大影响,操作起来很复杂。归并,那么需要找到链表的中间节点的位置,很显然用两个指针fast,slow一个走两步一个走一步就能搞定了。
指针的问题看起来简单,写起来难,merge函数中忘记处理head指针,错了一次,指针好用但难写。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *findMid(ListNode *head) { //找出链表中间节点
ListNode *fast = head->next;
ListNode *slow = head;
while(fast != NULL && fast->next != NULL){
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
ListNode* merge(ListNode *left,ListNode *right){ //归并,注意处理的过程中head首节点为空,因此最后需要返回head->next
ListNode *head = (ListNode *)malloc(sizeof(ListNode));
ListNode *res = head; //注意保留head指针,这里忘记处理WA了
while (left != NULL && right != NULL) {
if (left->val < right->val) {
head->next = left;
left = left->next;
} else {
head->next = right;
right = right->next;
}
head = head->next;
}
if (left != NULL) {
head->next = left;
} else {
head->next = right;
}
return res->next;
}
void createList(ListNode *&head){ //创建链表
int x;
while(scanf("%d",&x) != EOF){
if(x == 0) break;
ListNode *node = (ListNode *)malloc(sizeof(ListNode));
node->next = NULL;
node->val = x;
if(head == NULL) {
head = node;
} else {
node->next = head;
head = node;
}
}
}
void printList(ListNode *head){ //打印
while(head != NULL){
cout<<head->val<<" ";
head = head->next;
}
cout << endl;
}
ListNode* reverseList(ListNode *head){ //链表反转
if(head == NULL || head->next == NULL){
return head;
}
ListNode *tail = head, *temp = NULL,*cur;
while(tail->next != NULL){
cur = tail->next;
tail->next = temp;
temp = tail;
tail = cur;
}
tail->next = temp;
return tail;
}
ListNode *sortList(ListNode *head) {
if(head == NULL){
return NULL;
}
if(head->next == NULL){
return head;
}
ListNode *left,*right,*mid;
mid = findMid(head);
right = sortList(mid->next); //下面三行代码的顺序需要注意
mid->next = NULL;
left = sortList(head);
return merge(left,right);
}
};
int main()
{
ListNode *head = (ListNode *)malloc(sizeof(ListNode));
head = NULL;
Solution s;
s.createList(head);
s.printList(head);
head = s.sortList(head);
s.printList(head);
head = s.reverseList(head);
s.printList(head);
return 0;
}