LeetCode 61. Rotate List

来源:互联网 发布:linux oracle 中文乱码 编辑:程序博客网 时间:2024/04/29 15:46

https://leetcode.com/problems/rotate-list/

一直想给LeetCode 的题目描述跪, 一直说不清楚。此题一个坑是:k >= length(链表),只要k%=n就行,当然这个时候还有坑 n==0

#include <cstdio>#include <cstring>#include <string>#include <algorithm>#include <vector>#include <map>#include <iostream>using namespace std;  struct ListNode {      int val;      ListNode *next;      ListNode(int x) : val(x), next(NULL) {}  };class Solution {public:    int calLen(ListNode *head) {        int ret =0;        while(head) {            head = head -> next;            ret ++;        }        return ret;    }    ListNode* rotateRight(ListNode* head, int k) {        int n = calLen(head);        if(n)k %= n;        if( k == 0 || head == NULL) return head;        ListNode *first = head, *preFir = NULL, *ret=NULL;        for(int i=0;i<k;i++) {            if(first) {                preFir=first, first = first->next;            } else {                return head;            }        }        ListNode *second = head, *preSec = NULL;        while(first) {            preFir=first;            first = first -> next;            preSec = second;            second = second -> next;        }        if(preSec) {            preSec -> next = NULL;        } else { // k == n            return head;        }        preFir -> next = head;//        cout << "preFir = " << preFir->val << endl;//        cout << "preSec = " << preSec->val << endl;//        cout << "head = " << head->val << endl;//        show(second);//        cout << "((((((((((" << endl;        return second;    }    ListNode *createFromVector (vector <int> ivec) {        ListNode *ret = NULL, *pre=NULL, *head=NULL;        for(int i=0;i<ivec.size();i++) {            pre = ret;            ret = (ListNode *) malloc ( sizeof(ListNode) );            //pre -> next = ret;            ret->val = ivec[i];            if(i == 0) pre = head = ret;            else pre -> next = ret;            //cout << ret->val << endl;        }        ret -> next = NULL;        //show(head);        return head;    }    void show(ListNode *head) {        while(head) {            cout << "show = " << head->val << endl;            head = head->next;        }        cout << "******************" << endl;    }};int main() {    freopen("61.txt", "r", stdin);    int n,k, in;    while(cin >> n >> k) {        vector <int> ivec;        for(int i=0;i<n;i++) {            cin >> in;            ivec.push_back(in);        }        Solution s;        ListNode *head = s.createFromVector(ivec);        s.show( s.rotateRight(head, k) );    }    return 0;}




0 0
原创粉丝点击