leetcode61-Rotate List

题目

给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。

示例 1:

输入:head = [1,2,3,4,5], k = 2

输出:[4,5,1,2,3]

分析

这道题目用快慢指针即可解,先快指针往前走k个位置,然后和慢指针同时开始遍历,直到快指针的next为空。这个时候慢指针的next就是最新的头结点。这里要注意k比链表总长度大的情况,可以通过求余解决

java 复制代码
public class LinkNode {
	int val;
	LinkNode next;

	public LinkNode(int data) {
		this.val = data;
		this.next = null;
	}
}
public class LinkList {
	LinkNode head;
	public LinkList() {
		this.head = null;
	}
	public LinkNode getHead() {
		return this.head;
	}
	//添加元素
	public void addNode(int data) {
		LinkNode node = new LinkNode(data);
		if (this.head == null) {
			this.head = node;
		} else {
			LinkNode cur = this.head;
			while(cur.next != null) {
				cur = cur.next;
			}
			cur.next = node;
		}
	}
	//正序打印
	public void print(LinkNode node) {
		while(node != null) {
			System.out.print(node.val);
			System.out.print(" ");
			node = node.next;
		}
		System.out.println();
	}
	public void rotate(int k) {
		if(this.head == null) {
			return;
		}
		LinkNode p = this.head;
		int cnt = 0;
		while(p!= null) {
			cnt++;
			p = p.next;
		}
		k = k % cnt;
		LinkNode fast = this.head;
		LinkNode slow = this.head;
		for(int i = 0;i<k;i++) {
			fast = fast.next;
		}
		while(fast.next != null) {
			fast = fast.next;
			slow = slow.next;
		}
		fast.next = head;
		fast = slow.next;
		slow.next = null;
		print(fast);
	}
}

public class rotateList {
	public static void main(String[] args) {
		LinkList list = new LinkList();
		list.addNode(1);
		list.addNode(2);
		list.addNode(3);
		list.addNode(4);
		list.addNode(5);
		list.rotate(2);
	}
}
相关推荐
JavaGuide11 分钟前
一款悄然崛起的国产规则引擎,让业务编排效率提升 10 倍!
java·spring boot
吃虫子的人16 分钟前
记录使用Arthas修改线上源码重新加载的一次过程
java·arthas
数智工坊43 分钟前
【数据结构-树与二叉树】4.6 树与森林的存储-转化-遍历
数据结构
figo10tf43 分钟前
Spring Boot项目集成Redisson 原始依赖与 Spring Boot Starter 的流程
java·spring boot·后端
zhangyi_viva1 小时前
Spring Boot(七):Swagger 接口文档
java·spring boot·后端
橙露1 小时前
Spring Boot 核心原理:自动配置机制与自定义 Starter 开发
java·数据库·spring boot
小程故事多_801 小时前
Agent Infra核心技术解析:Sandbox sandbox技术原理、选型逻辑与主流方案全景
java·开发语言·人工智能·aigc
冰暮流星1 小时前
sql语言之分组语句group by
java·数据库·sql
望舒5131 小时前
代码随想录day25,回溯算法part4
java·数据结构·算法·leetcode