leetcode:Rotate List

一、题目

给出一个链表,将右边k个节点移到前面。

返回4->5->1->2->3->NULL

二、分析

之前我们遇到过将字符右移或左移的,当时的思路是将前一部分反转,后一部分反转,整体再反转,即可得到结果。

不过这道题我们需要换一种思路,其实对于这种链表的问题,我们可以总结出,链表的反转都可以直接从某一个位置开始截断即可,,例如上面的这道题:

/** * 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) {if(head == NULL || k == 0)return head;int len = 1;ListNode *h;h = head;while(head->next != NULL){head = head->next;len++;}k = k%len;if(k == 0)return h;else {head->next = h;k = len – k;while(k–){head = head->next;}h = head->next;head->next = NULL;head = h;}return head;}};

轻轻的风,吹开你紧锁的眉头,

leetcode:Rotate List

相关文章:

你感兴趣的文章:

标签云: