栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Python

leetcode 旋转链表

Python 更新时间:发布时间: 百科书网 趣学号
leetcode 旋转链表实现 题目描述:给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。 python代码实现:
class Solution(object):
	# 此方法实现链表向右移动一位,则只需要调用k次此方法
    def rotate(self,head):
        if not head or not head.next:
            return head
        p = head
        q = p.next
        while q.next:
            p=p.next
            q=q.next
        #q 最后一个节点
        p.next=None
        q.next = head
        return q
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if not head:
            return head
        length=0
        cur = head
        while cur:
            length+=1
            cur = cur.next
        # 保证一次到位,不做重复工作
        k%=length
        j=0
        while j 

运行截图:

C语言代码实现:
struct ListNode* rotate(struct ListNode* head){
    if(head==NULL||head->next==NULL)
    return head;
    struct ListNode* p=head;
    struct ListNode* q=head->next;
    while(q->next!=NULL){
        p=p->next;
        q=q->next;
    }
    //q最后一个节点
    q->next=head;
    p->next=NULL;
    return q;
}
struct ListNode* rotateRight(struct ListNode* head, int k){
    struct ListNode* cur =head;
    int len=0;
    while(cur!=NULL){
            len++;
            cur=cur->next;
    }
    if(len==0||len==1){
        return head;
    }
    k%=len;
    int i=0;
    while(i
        head=rotate(head);
        i++;
    }
    return head;
}
            

运行截图:

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/987142.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号