LeeCode打卡第十六天
第一题:回文链表(LeeCode第234题):
给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
解法一:暴力求解法
主要思想:将链表中的所有元素存到数组中,然后数组首尾进行遍历,看是否相等,相等即为回文链表,不相等则返回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) {
List<Integer> list = new ArrayList<>();
ListNode p = head;
int n = 0;
while(p != null){
list.add(p.val);
p = p.next;
}
int start = 0;
int end = list.size() - 1;
for(; start < end;){
if(list.get(start++) != (list.get(end--))) return false;
}
return true;
}
}
解法二:快慢指针+反转链表
主要思想:经过简单模拟,让slow指针每次走一步,fast指针每次走两步fast和slow一起开始遍历,当fast遍历到链表最末尾的时候,skiw正处于链表的正中间,将slow指针后半段的链表进行翻转,将反转后的链表,与slow指针的前半段进行比较,看是否相等,相等即为回文链表
/**
* 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) {
if(head == null || head.next == null) return true;
ListNode fast = head, slow = head;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
fast = dfs(slow.next);
slow.next = null;
ListNode p1 = head, p2 = fast;
while(p2 != null){
if(p1.val != p2.val){
return false;
}
p1 = p1.next;
p2 = p2.next;
}
return true;
}
ListNode dfs(ListNode node){
ListNode dummyhead = new ListNode(-1);
ListNode cur = node;
ListNode tmp;
while(cur != null){
tmp = cur.next;
cur.next = dummyhead.next;
dummyhead.next = cur;
cur = tmp;
}
return dummyhead.next;
}
}
第一题:环形链表(LeeCode第141题):
给你一个链表的头节点 head ,判断链表中是否有环。如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。注意:pos 不作为参数进行传递 。仅仅是为了标识链表的实际情况。如果链表中存在环 ,则返回 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) {
List<Integer> list = new ArrayList<>();
ListNode p = head;
int n = 0;
while(p != null){
list.add(p.val);
p = p.next;
}
int start = 0;
int end = list.size() - 1;
for(; start < end;){
if(list.get(start++) != (list.get(end--))) return false;
}
return true;
}
}