考试结束,班级平均分只拿到了年级第二,班主任因而问道:你们都知道世界第一高峰珠穆朗玛峰,有人知道世界第二高峰是什么吗?正当班主任要继续发话,只听到角落默默想起来一个声音:”乔戈里峰”java
2018.11.6号打卡程序员
明天的题目:https://leetcode-cn.com/problems/remove-linked-list-elements/
之后明天的题目提取公布一下哈,由于有些朋友想提早作一下~面试
leetcode234-回文链表
中文连接:
https://leetcode-cn.com/problems/palindrome-linked-list/
英文链表:
https://leetcode.com/problems/palindrome-linked-list/
难度:easy
分类:链表编程
请判断一个链表是否为回文链表。测试
示例 1:spa
输入: 1->2
输出: false
示例 2:code
输入: 1->2->2->1
输出: trueblog
距离AC只差一个测试用例的错误思路element
代码leetcode
1/** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9class Solution { 10 public boolean isPalindrome(ListNode head) { 11 int sum1 = 0; 12 if(head == null || head.next == null) 13 return true; 14 int count = 1; 15 ListNode temp = head; 16 while(temp != null) 17 { 18 sum1 += count * temp.val; 19 count += 1; 20 temp = temp.next; 21 } 22 int sum2 = 0; 23 count = 1; 24 head = reverseList(head); 25 temp = head; 26 while(temp != null) 27 { 28 sum2 += count * temp.val; 29 count += 1; 30 temp = temp.next; 31 } 32 if(sum1 == sum2) 33 return true; 34 return false; 35 } 36 public ListNode reverseList(ListNode head) { 37 if(head == null || head.next == null) 38 return head; 39 ListNode pre = head; 40 ListNode pNode = head.next; 41 ListNode next = head; 42 //首先处理前两个节点; 43 pre.next = null; 44 while(pNode != null) 45 { 46 next = pNode.next; 47 pNode.next = pre; 48 pre = pNode; 49 pNode = next; 50 } 51 return pre; 52 } 53}
结果,差一个用例没过,说明这种方法仍是有点问题~~~~
dasda
正确的思路
代码
1/** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9class Solution { 10 public boolean isPalindrome(ListNode head) { 11 if(head == null || head.next == null) 12 return true; 13 int length = 0; 14 ListNode temp = head; 15 while(temp != null) 16 { 17 length++; 18 temp = temp.next; 19 } 20 int halfLength = length / 2; 21 temp = head; 22 for(int i=0;i<halfLength;i++) 23 temp = temp.next; 24 ListNode pre = temp; 25 ListNode pNode = temp.next; 26 ListNode next = pNode; 27 while(pNode != null) 28 { 29 next = pNode.next; 30 pNode.next = pre; 31 pre = pNode; 32 pNode = next; 33 } 34 for(int i=0;i<halfLength;i++) 35 { 36 if(head.val != pre.val) 37 return false; 38 head = head.next; 39 pre = pre.next; 40 } 41 return true; 42 } 43}
代码讲解
2018.11.6号 打卡
做者乔戈里亲历2019秋招,哈工大计算机本硕,百度准入职java工程师,欢迎你们关注个人WX公众号:程序员乔戈里,公众号有3T编程资源,以及我和我朋友(准入职百度C++工程师)在秋招期间整理的近200M的面试必考的java与C++面经,并有天天一道leetcode打卡群与技术交流WX群,欢迎关注。