给你一个单链表的头节点 head
,请你判断该链表是否为回文链表。如果是,返回 true
;否则,返回 false
。
编辑
代码如下:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public boolean isPalindrome(ListNode head) { ListNode newHead=new ListNode(); newHead=reverseList(head); while (head!=null){ if(newHead.val!=head.val){ return false; }else { head=head.next; newHead=newHead.next; } } return true; } //反转链表 public ListNode reverseList(ListNode head) { if(head==null|| head.next==null){ return head; } ListNode dummyHead=new ListNode(-1); while (head!=null){ ListNode node=new ListNode(head.val); node.next=dummyHead.next; dummyHead.next=node; head=head.next; } return dummyHead.next; } }
实现结果:
编辑