leetcode143-Reorder List

题目

给定一个单链表 L 的头节点 head ,单链表 L 表示为:

L0 → L1 → ... → Ln - 1 → Ln

请将其重新排列后变为:

L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → ...

不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例 1:

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

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

分析

这道题目的思路其实很明确,先把链表一分为二,再求第二个链表的翻转链表,再把俩个链表相互插入式的连接到一起即可。特别要注意处理一些边界情况,否则很容易空指针

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 insert() {
		if(this.head == null) {
			return;
		}
		int cnt = 0;
		LinkNode p = this.head;
		while(p != null) {
			cnt++;
			p = p.next;
		}
		cnt = cnt / 2;
		p = this.head;
		LinkNode tmpPre = null;
		while(cnt > 0) {
			cnt--;
			tmpPre = p;
			p = p.next;
		}
		tmpPre.next = null;
		LinkNode pre = null;
		while(p != null) {
			LinkNode next = p.next;
			p.next = pre;
			pre = p;
			p = next;
		}
		LinkNode first = this.head;
		LinkNode second = pre;
		while(first != null && second != null) {
			LinkNode secondNext = second.next;
			LinkNode firstNext = first.next;
			if(firstNext == null) {
				first.next = second;
				break;
			}
			second.next = firstNext;
			first.next = second;
			if(firstNext == null) {
				first.next = second;
				break;
			}
			first = firstNext;
			second = secondNext;
			if(first.next == null) {
				first.next = second;
				break;
			}
		}
		print(this.head);
	}

}

public class reorderList {
	public static void main(String[] args) {
		LinkList list = new LinkList();
		list.addNode(1);
		list.addNode(2);
		list.addNode(3);
		list.insert();
	}
}
相关推荐
LinuxSuRen2 小时前
Docker Compose Provider 服务介绍
java·运维·docker·容器·eureka
sg_knight3 小时前
Docker网络全景解析:Overlay与Macvlan深度实践,直通Service Mesh集成核心
java·网络·spring boot·spring cloud·docker·容器·service_mesh
好想有猫猫3 小时前
【Redis】List 列表
数据库·c++·redis·分布式·缓存·list
鬣主任4 小时前
JavaSenderMail发送邮件(QQ及OFFICE365)
java·spring boot·smtp/imap/tls
找不到、了5 小时前
关于ReadWriteLock读写锁的介绍
java·开发语言·jvm
汉得数字平台6 小时前
集星獭 | 重塑集成体验:新版编排重构仿真电商订单数据入库
java·重构·idea·paas·源代码管理
亲爱的马哥6 小时前
TDuckX 2.6 正式发布|API 能力开放,核心表单逻辑重构,多项实用功能上线。
java·服务器·前端
Themberfue6 小时前
RabbitMQ ⑤-顺序性保障 || 消息积压 || 幂等性
java·分布式·消息队列·rabbitmq
白开水不加冰6 小时前
Spring的BeanFactory和FactoryBean的区别
java·后端·spring
旋风菠萝6 小时前
八股文--JVM(2)
java·jvm·八股文·java八股