博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Leetcode]旋转链表
阅读量:4580 次
发布时间:2019-06-09

本文共 1301 字,大约阅读时间需要 4 分钟。

题目

 

代码 

/** * 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==nullptr)       return nullptr;		auto ptr = head;		int length = 0;		while (ptr != nullptr)		{			ptr = ptr->next;			length++;		}        k=k%length;     if(k==0)       return head;		//54321 2		auto newHead = ReverseList(head, length);     if(k==length)       return newHead;		//45321 2		newHead = ReverseList(newHead, k);		//45123 2		int num = k;		auto nextHead = newHead;		while (num > 0)		{			nextHead = nextHead->next;			num--;		}		auto nextNewHead=ReverseList(nextHead, length - k);		auto connPtr = newHead;		while (k > 1)		{			connPtr = connPtr->next;			k--;		}		connPtr->next = nextNewHead;		return newHead;	}	/*   * head 开始结点   * num 翻转的个数   * return 反转后的头结点   */	ListNode* ReverseList(ListNode*head, int num)	{		if (head == nullptr || num == 0)			return nullptr;		auto realTail = head;		ListNode* newHead = nullptr;		ListNode* temp = nullptr;		while (num>0)		{			temp = head->next;			head->next = newHead;			newHead = head;			head = temp;			num--;		}		realTail->next = temp;		return newHead;	}};

 

转载于:https://www.cnblogs.com/lizhenghao126/p/11053559.html

你可能感兴趣的文章
颜色分类函数
查看>>
(中等) HDU 4725 The Shortest Path in Nya Graph,Dijkstra+加点。
查看>>
sort-归并排序
查看>>
django 快速实现完整登录系统(cookie)
查看>>
.NET中的out和ref关键字
查看>>
Python之ftp服务器
查看>>
KMP预处理
查看>>
oracle的wm_concat函数实现行转列
查看>>
C语 三子棋小游戏
查看>>
[BZOJ 1861] 书架
查看>>
送给毕业生的一个学习建议
查看>>
基于redis+lua实现高并发场景下的秒杀限流解决方案
查看>>
Oracle 块修改跟踪 (Block Change Tracking) 说明
查看>>
阿里云 Redis 服务遇到的问题
查看>>
Jwt Token 安全策略使用 ECDSA 椭圆曲线加密算法签名/验证
查看>>
Window2008通过web.config进行限制ip访问
查看>>
浅析门户网站体育赛事CDN加速解决方案
查看>>
启动/关闭xp_cmdshell
查看>>
[PY3]——内置数据结构(8)——解构与封装
查看>>
进程、单线程和多线程
查看>>