4 ms in C code, easy to understand


  • 0
    X
    struct ListNode* rotata(struct ListNode *head) {
    	struct ListNode *cur = head;
    	struct ListNode *prev = NULL;
    	if (head == NULL) return NULL;
    	if (head->next == NULL) return head;
    	while(cur->next) {
    		prev = cur;
    		cur = cur->next;
    	}
    	prev->next = NULL;
    	cur->next = head;
    	return cur;
    }
    struct ListNode* rotateRight(struct ListNode* head, int k) {
    	int count = 0;
    	struct ListNode *cur = head;
    	if (head == NULL) return head;
    	while(cur) {
    		cur = cur->next;
    		count++;
    	}
    	cur = head;
    	if (k >= count) k %= count;
    	while(k--) cur = rotata(cur);
    	return cur;
    }

  • 0
    L

    share my o(n) code

    class Solution {
        public:
            ListNode* rotateRight(ListNode* head, int k) 
            {
                if(!head||!head->next)return head;
                 deque<ListNode*> temp;
                 ListNode *start=head,*end=head;
                 int lth=0;
                 while(start)
                 {
                     lth++;
                     temp.push_back(start);
                     start=start->next;
                 }
                 start=head;
                 k=k%lth;
                 while(k--)
                 {
                     end=temp.back();
                     temp.pop_back();
                     temp.push_front(end);
                     end->next=start;
                     start=end;
                 }
                 temp.back()->next=nullptr;
                 return temp[0];
            }
        };

  • 0

    头节点指的是第一个节点还是,指向第一个节点的ListNode?一直对这个概念迷糊


  • 0
    X

    第一个节点的listnode


  • 0
    X

    第一个节点的listnode


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.