61. 旋转链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* rotateRight(struct ListNode* head, int k)
{
    if (head == NULL || head->next == NULL || k == 0) {
        return head;
    }
    int len = 0;
    struct ListNode* tail = head;
    while (tail && tail->next) {
        len++;
        tail = tail->next;
    }
    len++;

    if (k % len == 0) {
        return head;
    }
    
    k = len - (k % len);
    tail->next = head;

    while (k--) {
        tail = tail->next;
        head = head->next;
    }

    tail->next = NULL;
    return head;
}

 

148. 排序链表

暴力解法:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

int Cmp(const void *a, const void *b)
{
    return (*(int *)a) - (*(int *)b);
}

struct ListNode* sortList(struct ListNode* head)
{
    int *arr = (int *)malloc(sizeof(int) * 50000);
    struct ListNode* tmp = head;
    int len = 0;
    while (tmp) {
        arr[len++] = tmp->val;
        tmp = tmp->next;
    }

    qsort(arr, len, sizeof(int), Cmp);
    
    tmp = head;
    for (int i = 0; i < len; i++) {
        tmp->val = arr[i];
        tmp = tmp->next;
    }

    return head;
}

 

更多文章请关注《万象专栏》