61-Rotate list

来源:互联网 发布:什么盒子能接猫的网络2 编辑:程序博客网 时间:2024/06/05 15:07

难度:medium
类别:linked list

1.题目描述

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.

2.算法分析

(1)处理链表为空以及链表只有一个节点的情况
(2)k的值可能超过count,所以k %= count
(3)处理断开处前一个节点的next
(4)让最后一个节点的next指向head

3.代码实现

#include <iostream>using namespace std;struct ListNode {    int val;    ListNode *next;    ListNode(int x) :val(x), next(NULL) {}};ListNode* rotateRight(ListNode* head, int k) {    if (head == NULL || head->next == NULL) return head;    int count = 0;    // count list length    ListNode* temp = head;    while (temp != NULL) {        count++;        temp = temp->next;    }    //  k may > count;    k = k % count;    if (k == 0) return head;    int num = 1;    temp = head;    // 断开处的next处理    while (num != count - k) {        num++;        temp = temp->next;    }    ListNode* begin = temp->next;    ListNode* result = begin;    temp->next = NULL;    while (begin->next != NULL) {        begin = begin->next;    }    // 尾部节点的next设置为head    begin->next = head;    return result;}void printList(ListNode* head) {    while (head != NULL) {        cout << head->val << " ";        head = head->next;    }    cout << endl;}int main() {    int n, num, k;    cin >> n >> k;    ListNode* head = NULL;    ListNode* temp = NULL;    for (int i = 0; i < n; ++i) {        cin >> num;        if (i == 0) {            head = new ListNode(num);            temp = head;        }        else {            head->next = new ListNode(num);            head = head->next;        }    }    printList(temp);    temp = rotateRight(temp, k);    printList(temp);    system("pause");    return 0;}
原创粉丝点击