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();
	}
}
相关推荐
lexiangqicheng几秒前
1,自定义表单通俗理解-PC设计APP渲染
java·前端·javascript
南极企鹅9 分钟前
生产环境gc文件分析
java·jvm·算法
Wang's Blog9 分钟前
Java 项目实战: 交友项目 - 前后端分离的工程实践
java·spring cloud·架构
希洛兔11 分钟前
原码、反码、补码:一张图讲透计算机里的负数表示
算法·面试
benchmark_cc11 分钟前
批量获取股票数据后,如何统一转换成 DataFrame?从数据结构到量化研究的完整实践
数据结构·python·数据分析·量化交易·股票数据·quantdash
溪语流沙18 分钟前
面试加分项!Manacher:O(n)求最长回文子串的对称之美
java·python·leetcode·面试·职场和发展
知守观19 分钟前
Maven SNAPSHOT 更新排查:-U 无效、clean 无用,问题在 _remote.repositories(附完整链路)
java·后端·maven
牛战士coding20 分钟前
从一句\“取消订单\“到退款通知:AI 写操作完整业务闭环
java·人工智能
啵啵啵鱼21 分钟前
第三章 栈、队列和数组相关结构
java·数据结构·栈·队列