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.


pro:给一个链表,和一个k,要求将链表整体向右rotate k个位置,就是整体循环向右移动k个位置。也就是右边k个节点移到左边。

sol:

1.首先需要知道链表长度len。k有可能大于len,所以k=k%len。左边有left=len-k%len个节点,右边有k%len个节点。

2.第二步就是从head开始找到第left个位置。找到这两段的首末位置,将指针指一下就好。在原链表中两段表示为(head,cur),(cur->next,last)。

code:

class Solution {
public:
    ListNode *rotateRight(ListNode *head,int k)
    {
        if(head==NULL) return head;
        ListNode *cur,*last;
        int i,length;
        length=0;
        cur = head;
        while(cur!=NULL)
        {
            if(cur->next==NULL)
                last = cur;
            length++;
            cur = cur->next;
        }
        if(k%length==0) return head;
        k = length - k%length;
        cur = head;
        for(i=1;i<k;i++)
            cur = cur->next;
        last->next = head;
        head = cur->next;
        cur ->next = NULL;
        return head;
    }
};




### 代码功能理解 这段Python代码定义了一个名为 `rotate_block` 的函数,该函数的主要目的是对一个方块进行旋转操作。函数接收一个事件参数 `event`,但在函数体中并未使用该参数。函数使用了全局变量 `current_block`,如果 `current_block` 为 `None`,则函数直接返回。接着,函数从 `current_block` 中提取 `cell_list`,并对其中的每个单元格进行旋转操作,将旋转后的单元格添加到 `rotate_list` 中。最后,函数创建一个新的方块字典 `block_after_rotate`,其中包含旋转后的单元格列表。 ### 代码存在的问题 1. **未使用的参数**:函数定义中的 `event` 参数在函数体中未被使用,这可能是代码设计上的失误。 2. **未返回结果**:函数没有返回旋转后的方块 `block_after_rotate`,调用该函数后无法获取旋转后的方块。 3. **全局变量的使用**:使用全局变量 `current_block` 可能会导致代码的可维护性和可测试性降低,因为全局变量的状态可能会在代码的其他部分被意外修改。 ### 代码优化建议 1. **移除未使用的参数**:如果 `event` 参数确实不需要,可以将其从函数定义中移除。 2. **返回旋转后的方块**:在函数的末尾添加 `return block_after_rotate` 语句,以便调用者可以获取旋转后的方块。 3. **避免使用全局变量**:可以将 `current_block` 作为参数传递给函数,而不是使用全局变量。 ### 优化后的代码 ```python def rotate_block(current_block): if current_block is None: return None cell_list = current_block['cell_list'] rotate_list = [] for cell in cell_list: cell_c, cell_r = cell rotate_cell = [cell_r, -cell_c] rotate_list.append(rotate_cell) block_after_rotate = {'kind': current_block['kind'], 'cell_list': rotate_list} return block_after_rotate ``` ### 优化说明 - 移除了未使用的 `event` 参数。 - 避免了使用全局变量,将 `current_block` 作为参数传递给函数。 - 添加了 `return block_after_rotate` 语句,以便调用者可以获取旋转后的方块。 ### 代码进一步优化 可以使用列表推导式来简化旋转操作的代码: ```python def rotate_block(current_block): if current_block is None: return None cell_list = current_block['cell_list'] rotate_list = [[cell[1], -cell[0]] for cell in cell_list] block_after_rotate = {'kind': current_block['kind'], 'cell_list': rotate_list} return block_after_rotate ``` ### 优化说明 - 使用列表推导式替代了 `for` 循环,使代码更加简洁。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值