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
原创粉丝点击