One-way linked list Rotation

Source: Internet
Author: User

Given a one-way linked list, an algorithm is designed to rotate the linked list K places to the right.

Example:

Given: 1-> 2-> 3-> 4-> 5-> 6-> null and K = 3,

4-> 5-> 6-> 1-> 2-> 3-> null.

struct Node{    int value;    Node *next;};Node* revert(Node *head, unsigned int k){    if (head == NULL         || k == 0)    {        return head;    }    int len = 0;    Node *p = head;    Node *q = head;    while (p->next != NULL)    {        len++;        p = p->next;        if (len >= k+1)        {            q = q->next;        }    }    Node *tail = p;    if (k%(len+1) == 0)    {        return head;    }    if (len+1 > k)    {        tail->next = head;        Node *temp = q->next;        q->next = NULL;        return temp;    }    p = head;    k = k%(len+1);    int steps = len-k;    while (steps)    {        p = p->next;        steps--;    }    tail->next = head;    Node *temp = p->next;    p->next = NULL;    return temp;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.