leetcode 回文链表

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false

示例 2:

输入: 1->2->2->1
输出: true

进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

解题思路:

1. 先把链表一分为二。

2. 把后半段进行反转链表(此处调用了写的回文链表方法)

3. 将反转后的链表和前半部分依次比对,如果相同,就是回文链表。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
		 if(head==null || head.next==null) {
			 return true;
		 }
		 //先将链表一分为二,两部分
		 ListNode fast = head.next;
		 ListNode slow = head;
		 ListNode mid = null;
		 //这样当fast走到最后一位或者倒数第二位,就结束了
		 while(fast!=null && fast.next!=null) {
			 fast = fast.next.next;
			 slow = slow.next;
		 }
		//如果是奇数个节点,fast=null
		 if(fast==null) {
			//反转后面两个
			 mid = reverseList(slow);
		 }else {
			 mid =  reverseList(slow.next);
		 }
		 
//		//如果是偶数个节点,fast.next=null
//		 if(fast.next==null) {
//			//反转后面两个
//			mid =  reverseList(slow.next);
//		 } 
		 //比较head和mid
		 while(mid!=null) {
			 if(mid.val != head.val) {
				 return false;
			 }
			 mid = mid.next;
			 head = head.next;
		 }
		
		 return true;	        
	    
    }
    
    public  ListNode reverseList(ListNode head) {
	//如果是空节点和单节点,要返回该节点
	if(head==null ) {
		return head;
	}
	if(head.next == null ) return head;
	//如果不是空节点,返回的肯定是对下一个节点的递归。但是要先处理该节点
	//该节点的从头开始,让第二个节点指向第一个,第一个节点指向空,表示尾节点
	ListNode second = head.next;
	ListNode nextnode = reverseList(second);  //对下一节点进行递归
	
	second.next = head;
	head.next=null;

	//返回下一节点的递归
	return nextnode ;
}	
    
}

猜你喜欢

转载自blog.csdn.net/a627082796/article/details/86504300