61. Rotate List

来源:互联网 发布:windows访问samba 编辑:程序博客网 时间:2024/06/10 15:07

题目

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.

思路

本题,右旋,比较简单,考察了指针的操作

代码

/** * 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)            return head;        ListNode* Head = new ListNode(0);        Head->next = head;        ListNode* headcopy = head;        int count =0;        while(headcopy->next)        {            count++;            headcopy = headcopy->next;        }        count++;        k %=count;        if(k==0)            return head;        count -= k;        for(int i=2;i<=count;i++)        {            head = head->next;        }        ListNode* temp = Head->next;        Head->next = head->next;        head->next = NULL;        headcopy->next = temp;        return Head->next;          }};
原创粉丝点击