Everyone thinks of changing the world, but no one thinks of changing himself.
每一个人都想要改变世界,却没人想过要改变本身。
上海自来水来自海上,中山诸罗茶罗诸山中。很是有意境的句子,正着读倒着读都是一个意思。很是对陈,强迫症患者福音。本文分享了基于单链表判断回文的三种方法。全部源码均已上传至github:连接java
可是这种数组的倒序插入比较费时。node
小技巧:一直使用node.add(0,slow.data)至关于倒序插入git
private boolean isPalindromeByArray(Node node) {
if (null == node || null == node.next) return true;
List<Integer> nodeList = new ArrayList<>();
Node fast = node;
Node slow = node;
nodeList.add(0, slow.data);
while (null != fast.next && null != fast.next.next) {
fast = fast.next.next;
slow = slow.next;
nodeList.add(0, slow.data);
}
Node curNode = slow;
if (null != fast.next) {
curNode = slow.next;
}
int index = 0;
while (null != curNode) {
if (curNode.data != nodeList.get(index)) {
return false;
}
curNode = curNode.next;
++index;
}
return true;
}复制代码
private boolean isPalindromeByStack(Node node) {
if (null == node || null == node.next) return true;
Stack<Integer> stack = new Stack<>();
Node fast = node;
Node slow = node;
stack.push(slow.data);
while (null != fast.next && null != fast.next.next) {
fast = fast.next.next;
slow = slow.next;
stack.push(slow.data);
}
if (null != fast.next) {
slow = slow.next;
}
Node curNode = slow;
while (null != curNode) {
if (curNode.data != stack.pop()) {
return false;
}
curNode = curNode.next;
}
return true;
}复制代码
private boolean isPalindromeAuto(Node node) {
if (null == node || null == node.next) return true;
Node fast = node;
Node slow = node;
while (null != fast.next && null != fast.next.next) {
fast = fast.next.next;
slow = slow.next;
}
Node preNode = slow;
Node firstNode = slow.next;
Node curNode = slow.next.next;
firstNode.next = null;
while (null != curNode) {
Node nextNode = curNode.next;
curNode.next = preNode.next;
preNode.next = curNode;
curNode = nextNode;
}
slow = node;
fast = preNode.next;
while (null != fast) {
if (fast.data != slow.data) {
return false;
}
slow = slow.next;
fast = fast.next;
}
return true;
}复制代码
您的点赞和关注是对我最大的支持,谢谢!