LeetCode 20200203(旋转链表)

我是研究僧i 提交于 2020-02-06 01:07:01

1.旋转链表
这道题做过一遍了 很简单 就是对链表的基本操作
计算链表的长度 然后找到要截断的地方
进行重组
记得写一个虚拟头结点 重组 即可

/**
 * 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 || head->next==NULL || k==0){return head;}
        ListNode* phead=new  ListNode(0);
        phead->next=head;
        ListNode* q=phead;
        int len=0;
        while(q->next!=NULL){
            q=q->next;
            len++;
        }
        k= k % len;
        if(k==0){return head;}
        ListNode* bre=phead;
        for(int i=0;i<len-k;i++){
            bre=bre->next;
        }
        phead->next=bre->next;
        q->next=head;
        bre->next=NULL;
        return phead->next;

    }
};
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!