2.7 Implement a function to check if a linked list is a palindrome
来源:互联网 发布:淘宝怎么搜漏洞券 编辑:程序博客网 时间:2024/06/10 04:47
方法1 找到长度len,然后从一半开始和stack中元素比对
方法2 fast node ,slow node,hit 到终点为slow到一半
package test;
//Implement an algorithm to find the kth to last element of a singly linked list.
import java.util.Scanner;
import java.util.Stack;
//import java.util.HashSet;
public class JumpTwo {
static class Node {
char data;
Node next = null;
Node(char a) {
this.data = a;
}
}
public static void main(String[] args) {
Scanner input1 = new Scanner(System.in);
StringBuffer sb = new StringBuffer(input1.nextLine());
String s = sb.toString();
char[] chars = s.toCharArray();
Node p = new Node('1');
Node head = p;
for (char c : chars) {
p.next = new Node(c);
p = p.next;
}
head = head.next;
if (isPalindrome(head)) {
System.out.println("ture");
} else {
System.out.println("false");
}
}
private static boolean isPalindrome(Node head) {
Node n1 = head;
Stack<Character> st = new Stack<Character>();
int len = 0, mid = 0;
int i = 0;
boolean od = true;
while (n1 != null) {
len++;
n1 = n1.next;
}
n1 = head;
if (len % 2 == 0) {
mid = len / 2;
od = false;
} else {
mid = (len - 1) / 2;
}
while (n1 != null) {
if (i < mid) {
st.push(n1.data);
n1 = n1.next;
}
else if(od && i==mid){
n1 = n1.next; // odd case; skip the middle one
}
else if(i>mid){
if (st.pop() != n1.data) {
return false;
} else {
n1 = n1.next;
}
}
i++;
}
return true;
}
}
0 0
- 2.7 Implement a function to check if a linked list is a palindrome
- Check if a linked list is palindrome
- Q4.1 Implement a function to check if a tree is balanced
- Q2.7 Check if a list is a palindrome
- LinkLists 检查一个链表是否为回文 Check if a linked list is palindrome @CareerCup
- Check whether a string is a palindrome
- Check if a string value is numeric
- How To: Check if a user is part of a SharePoint group in InfoPath
- A program to check if a binary tree is BST or not
- Is there a way to check if android WindowManager already contains a view?
- 判断一个整数是否为回文数 Check if a number is palindrome
- What is the best way to implement a heartbeat in C++ to check for socket connectivity?
- Given an integer, write a function to determine if it is a power of two.
- Given an integer, write a function to determine if it is a power of two
- Given two binary trees, write a function to check if they are equal or not.
- C Program to Implement a Doubly Linked List & provide Insertion, Deletion & Display Operations
- Q.2.3 Implement an algorithm to delete a node in the middle of a single linked list, given only acce
- Makefile – Check if a file exists using wildcard function
- 移动互联网精彩语录:悟透一句话,改变你一生!
- iOS 面试题:OC基本概念题
- 写给我的2014级学生
- Other Monitors for Detailed Analysis ST02
- VS2012 Form + OpenCV
- 2.7 Implement a function to check if a linked list is a palindrome
- BZOJ 3544 ONTAK 2010 Creative Accounting 贪心+平衡树
- 往数据库中添加照片
- insert into 语句总是出现 未指定错误
- 用EmEditor快速删除段首、段尾空格
- 记录集元素个数
- C# 获取文件名及扩展名
- Java 课堂随笔 (4)
- 杂碎-参考博文