• Rotate List


    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.

    思路:这道题循环右移链表k个结点。主要是考察对链表指针的熟悉程度。

    1.计算链表的长度以及记录链表的尾指针,同时k%=lenght;

    2.找出从尾部数第k个结点,然后该表链表的指向;

    /**
     * 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;
            int length=0;
            ListNode *pCur=head;
            ListNode *pTail=head;
            while(pCur!=NULL)
            {
                length++;
                pTail=pCur;
                pCur=pCur->next;
            }
            k%=length;
            pCur=head;
            for(int i=0;i<length-k-1;i++)
                pCur=pCur->next;
            pTail->next=head;
            head=pCur->next;
            pCur->next=NULL;
            return head;
        }
    };
  • 相关阅读:
    单链队列
    栈的顺序存储表示
    顺序队列
    串的定长顺序存储表示
    串的堆分配存储
    双向循环链表
    单循环链表的表示和实现
    串的块链存储表示
    线性表的顺序表示和实现
    线性表的单链表表示和实现
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3750091.html
Copyright © 2020-2023  润新知