算法升级之路(一)

写算法的两个网站

  • collabedit.com
  • coderpad.io

推荐书

outliers《异类-不一样的成功启示录》
fibonacci array
1,1,2,3,5,8,13,21,33,52
master Theorem 主定律

切题四件套

  1. 所有的数字
  2. 所有的算法
  3. 时间复杂度
  4. pycharm

单链表反转
12345-》54321

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur = head;
ListNode prev = null;
while(cur != null){
ListNode next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}
}

递归实现

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public ListNode reverseList(ListNode head) {
if(head ==null||head.next==null){
return head;
}
ListNode node =reverseList(head.next);
head.next.next = head;
head.next =null;
return node;

}
}

链表两两反转
12345-》21435

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//节点移动
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode prev = null;
ListNode cur = head;
ListNode next = null;
ListNode a = null;
while(cur != null && cur.next != null ){
next = cur.next;
if(prev != null){
prev.next = next;
}else{
a = head.next;
}
cur.next = next.next;
next.next = cur;
prev = cur;
cur = cur.next;
if(cur != null){
next = cur.next;
}
}
return a;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
//改数
class Solution {
public ListNode swapPairs(ListNode head) {

ListNode result = head;

while (head != null && head.next != null) {
int temp = head.next.val;
head.next.val = head.val;
head.val = temp;
head = head.next.next;
}
return result;
谢谢您的鼓励~