Rotate List ,反转链表的右k个元素
2024-09-29 11:44:40
问题描述:
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是可以超过链表长度的,所以要对k取模。
public ListNode rotateRight(ListNode head, int k) {
int lenth = 0;//链表长度
ListNode headd = head;
while (headd != null) {
lenth++;
headd = headd.next;
}
if (head == null || head.next == null || k % lenth == 0) {
return head;
} ListNode headc = head;
for (int i = 1; i < lenth - k % lenth; i++) {
headc = headc.next;
}
ListNode newHead = headc.next;
ListNode p = newHead;
while (p.next != null) {
p = p.next;
}
p.next = head;
headc.next = null; return newHead;
}
最新文章
- makfile
- tomcat 和servlet之间的关系
- rhel7初体验
- <;input type=";file";>;中怎设置那个按钮的样式
- pycharm如何调试scrapy
- pyhton与json,Xml
- SQL Server 2008 表值参数用法
- 让项目管理理论&ldquo;落地&rdquo;&mdash;&mdash;读《IT项目经理成长手记》有感
- WCF之契约
- 第二篇、微信程序尺寸rpx
- 创建一个目录info,并在目录中创建一个文件test.txt,把该文件的信息读取出来,并显示出来
- ServletInvocableHandlerMethod:167 - Error resolving argument
- 【转】ASP.NET MVC教程
- chapter 10 统计检验
- Mybatis基础学习(五)&mdash;缓存
- Windows上安装scapy
- C++中的const总结
- Redis闪退解决办法
- Oracle 18C DBCA建库报ora-01012错误
- django前篇