leetCode,LeetCode_Rotate List

 2023-10-18 阅读 29 评论 0

摘要: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.   巨沒勁的一道題,當k>length 時,我以為origin
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.

  巨沒勁的一道題,當k>length 時,我以為origin list 不動就行,結果好些case過不了,看了別人的代碼才知道要 k%= length 真心想不通為什么,也懶得弄這種惡心的東西。面試遇到這種題目直接問面試官這種奇葩情況怎么處理就行。?

/*** Definition for singly-linked list.* struct ListNode {*     int val;*     ListNode *next;*     ListNode(int x) : val(x), next(NULL) {}* };*/
class Solution {
public:ListNode *rotateRight(ListNode *head, int k) {// Start typing your C/C++ solution below// DO NOT write int main() functionif(head == NULL || k == 0) return head;ListNode *p, *q;p = head;q= p;while(q &&--k){q = q->next;}if(k >0 || NULL == q) return head; ListNode *pre = NULL;while(q->next){pre = p;p = p->next;q = q->next;}q ->next = head;head  = p;pre ->next = NULL;return head;}
};

  

leetCode,轉載于:https://www.cnblogs.com/graph/p/3258474.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/147828.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息