list_node * check(list_node * head) { //////在下面完成代码 stack<int> stk; list_node *p = head; while (p) { stk.emplace(p->val); p = p->next; } p = head; while (!stk.empty()) { if (stk.top() != p->val) { cout << "false"; return head; } stk.pop(); p = p->next; } cout << "true"; return head; }
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; class ListNode { public int val; public ListNode next; public ListNode(int val) { this.val = val; this.next = null; } } public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine().trim()); String[] strList = br.readLine().trim().split(" "); ListNode head = new ListNode(Integer.parseInt(strList[0])); ListNode cur = head; for(int i = 1; i < n; i++){ cur.next = new ListNode(Integer.parseInt(strList[i])); cur = cur.next; } System.out.println(isPalindrome(head, n)); } private static boolean isPalindrome(ListNode head, int len) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode slow = head, fast = head; while(fast != null && fast.next != null){ dummy = dummy.next; slow = slow.next; fast = fast.next.next; } // 得到左右链表 ListNode left = head; ListNode right = len % 2 == 1? slow.next: slow; // 断链 dummy.next = null; // 反转右链表 right = reverse(right); // 最后比较两个链表的元素 while(left != null){ if(left.val != right.val){ return false; }else{ left = left.next; right = right.next; } } return true; } private static ListNode reverse(ListNode head) { ListNode prev = null; ListNode cur = head; while(cur != null){ ListNode next = cur.next; cur.next = prev; prev = cur; cur = next; } return prev; } }
list_node * check(list_node * head) { //////在下面完成代码 list_node *p1=head; stack <list_node *> s; while(p1!=NULL) { s.push(p1); p1=p1->next; } list_node *p2=head; while(p2!=NULL) { p1=s.top(); if(p1->val!=p2->val) { cout<<"false"; return head; } s.pop(); p2=p2->next; } cout<<"true"; return head; }