Rotate List

来源:互联网 发布:网络风靡的性感骚彤彤 编辑:程序博客网 时间:2024/05/19 14:38

普通的链表问题

/** * 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 *p1 = head;        ListNode *p2 = head;        ListNode *p3 = head;        int count = 0;        /*通过循环得到链表的长度*/        while(p1!=NULL)        {            count++;            p2 = p1->next;            p1 = p2;        }        p1 = head;        p2 = head;        k = k % count;        if(k == 0) return head;        for(int i = 1;i<(count-k);i++)        {            p2 = p1->next;            p1 = p2;        }        head = p1->next;        p2 = p1->next;        p1->next = NULL;        p1 = p2;        while(p1->next!=NULL)        {            p2 = p1->next;            p1 = p2;        }        p1->next = p3;                return head;    }};


0 0
原创粉丝点击