这个专栏 我将分享每日做的算法题的解题思路 秋招加油!
这是第九天 !!
027 回文链表
题目
AC代码
class Solution {
public boolean isPalindrome(ListNode head) {
List<Integer> list = new ArrayList<>();
while(head != null){
list.add(head.val);
head = head.next;
}
int left = 0,right = list.size()-1;
while(left <= right){
if(list.get(left) != list.get(right)){
return false;
}
left++;
right--;
}
return true;
}
}
这道题通过list存储数值,然后在list上判断即可。
028 展平多级双向链表
题目
AC代码
class Solution {
List<Node> list = new ArrayList<>();
public Node flatten(Node head) {
dfs(head);
for(int i=0;i<list.size()-1;i++){
Node pre = list.get(i);
Node cur = list.get(i+1);
pre.next = cur;
cur.prev = pre;
pre.child = null;
}
return head;
}
public void dfs(Node head){
if(head == null) return;
list.add(head);
dfs(head.child);
dfs(head.next);
}
}
典型的DFS问题,需要先遍历child节点,再遍历next节点。
029 排序的循环链表
题目
AC代码
class Solution {
public Node insert(Node head, int insertVal) {
Node cur = null;
Node next = null;
Node realHead = null;
if(head == null){
head = new Node(insertVal);
head.next = head;
return head;
}
cur = head;
next = head.next;
while(cur.val <= next.val){
cur = cur.next;
next = next.next;
if(cur == head) break;
}
realHead = next;
while(next.val < insertVal){
cur = next;
next = next.next;
if(next == realHead)break;
}
cur.next = new Node(insertVal);
cur = cur.next;
cur.next = next;
return head;
}
}
找到真正的头节点,也就是最小的节点,然后从这个节点开始遍历,找到插入的位置,插入节点即可。
成功需要时间
不能一蹴而就
努力工作
坚持不懈
保持耐心