[LeetCode] Rotate List

来源:互联网 发布:看三维彩超数据分男女 编辑:程序博客网 时间:2024/06/15 14:09

Rotate List Given a list, rotate the list to the right by k places,
where k is non-negative.

For example: Given 1->2->3->4->5->NULL and k = 2, return
4->5->1->2->3->NULL.

题目的意思先梳理下,如果list的长度是sz那么k需要模sz k = k%sz;
这里正向处理会比较方便,以题目为例,k=2时,需要从前往后找到第sz-k=3个节点作为新的tail。新的头节点是tail->next。拼接的话是将原来的尾节点接到原来的头结点上。

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    int List_size(ListNode* head){        int sz= 0;        while(head){            ++sz;            head = head->next;        }        return sz;    }    ListNode* rotateRight(ListNode* head, int k) {        if(k==0||head ==NULL||head->next==NULL)    return head;        ListNode *phead = head;        ListNode *ptail = head;        int h_sz = List_size(phead);        phead = head;        if(k%h_sz==0)   return head;        k = h_sz-k%h_sz;        while(--k)            ptail = ptail->next;        phead = ptail->next;        ptail->next = NULL;        ptail = phead;        while(ptail->next)            ptail = ptail->next;        ptail->next = head;        return phead;    }};

需要注意的是一些退化的情况
1)输入为[]时都要直接返回head
2)输入k=0时说明不旋转,直接返回head
3) 如果list只有一个元素,无论k等于多少,都要返回head
这三个对应于 if(k==0||head ==NULL||head->next==NULL) return head;
4)k%h_sz==0说明旋转的长度是链表长度的整数倍,直接放回head.

8ms AC

0 0
原创粉丝点击