leetcode_11:链表

链表

链表翻转

反转一个单链表

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* pre = NULL;
        ListNode* tmp = NULL;
        while(head){
            tmp= head->next;
            head->next=pre;
            pre=head;
            head = tmp;
        }
        return pre;
    }
};

排序链表

在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。

思路: 用链表实现归并排序

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* merge(ListNode* nodes1, ListNode* nodes2){
        ListNode* head = new ListNode(0);
        ListNode* nodes = head;
        while(nodes1 && nodes2){
            if(nodes1->val < nodes2->val){
                nodes->next = nodes1;
                nodes1 = nodes1->next;
            }else{
                nodes->next = nodes2;
                nodes2 = nodes2->next;
            }
            nodes = nodes->next;
        }
        if(nodes1) nodes->next=nodes1;
        if(nodes2) nodes->next=nodes2;
        return head->next;
    }
    ListNode* sortList(ListNode* head) {
        if(head==NULL || head->next==NULL) return head;
        ListNode* tmp1 = head;
        ListNode* tmp2 = head->next;
        while(tmp2 && tmp2->next){
            tmp1 = tmp1->next;
            tmp2 = tmp2->next->next;
        }
        ListNode* right = sortList(tmp1->next);
        tmp1->next = NULL;
        ListNode* left =sortList(head);
        return merge(left, right);
    }
};

你可能感兴趣的:(链表,leetcode,数据结构)