算法 - 鏈表操做題目套路

0. 前言

簡單的題目,可是沒有練習過或者背過,可能反而也寫不出來,在面試中每每是在短期內就寫完,你沒有時間畫圖,沒有時間推演,這些都只能在腦子裏快速完成,有時候拼了好久,以爲仍是沒有感受,即便寫出來了,在事後的一週到一個月照樣會忘記,bug free地寫出來仍是很費力,做爲對此深有體會的,或許跟我同樣的有99%的人,像本文寫的鏈表反轉,若是能夠在圖上畫出來,那你就必定能夠寫的出來,由於邊界很簡單,相似有快速排序荷蘭國旗問題這些題目是國內面試級別上纔會考的,比起像flag公司,還差那麼一點,儘管本身在算法方面不是很開竅,包括在校招時候也練過很多題,可是我知道依然不多,並且對題目沒有記憶感,總以爲本身是個傻子,這麼簡單的題目,居然寫不出來,不過依然以爲考算法和數據結構的其實才是公司考覈程序員最公平最能考覈思惟的方式,說了這麼多,包括本人在內,一直在身邊各類算法大神碾壓中,也期待在走向全棧工程師的道路上,單純地從技術上,本身的算法和數據結構能愈來愈好把。程序員

1.經典題目,鏈表反轉

//遞歸方式
public ListNode reverseList(ListNode head) {
    if (head == null || head.next == null)
      return head;
    ListNode next = head.next;
    ListNode new_head = reverseList(next);
    next.next = head;
    head.next = null;
    return new_head;
}
//遍歷
public ListNode reverseList(ListNode head) {

    ListNode pre = null, cur = head,next = null;
    while( cur != null) {
        next = cur.next;
        cur.next = pre;
        pre = cur;
        cur = next;
    }

    return pre;
}

2.相鄰反轉,部分反轉

//反轉相鄰節點鏈表1234 2143,反轉5個的也相似
public ListNode swapPairs(ListNode head) {
  if (head == null || head.next == null)
    return head;
  
  ListNode newNode = head.next;
  head.next = swapPairs(head.next.next);
  newNode.next = head;
  return newNode;
}

//部分反轉,12345 m=2 n=4 14325
public ListNode reverseBetween(ListNode head, int m, int n) {
  if (m>= n) return head;
  ListNode dump = new ListNode(0);
  dump.next = head;
  ListNode pre = dump;
  for (int i = 1; i< m; i++) {
    pre = pre.next;
  }
  
  head = pre.next;
  for (int i=m;i<n;i++) {
    ListNode nex = head.next;
    head.next = nex.next;
    next.next = pre.next;
    pre.next = nex;
  }
  
  return dump.next;
}

3.鏈表求和

//兩個鏈表求和
//輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
//輸出:7 -> 0 -> 8
//緣由:342 + 465 = 807
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
       ListNode resultListNode = new ListNode(0);
       ListNode current = resultListNode;
       int carry = 0;
       while(l1 !=null || l2 !=null){
           int sum = carry;
           if(l1!=null){
               sum += l1.val;
               l1 = l1.next;
           }
           if(l2!=null){
               sum += l2.val;
               l2 = l2.next;
           }
           int val = sum < 10?sum:sum - 10;
           carry = sum < 10 ?0:1;
           current.next = new ListNode(val);
           current =  current.next;
       }
        if(carry  == 1){
            current.next = new ListNode(1);
        }
        return resultListNode.next;
    }

吳邪,小三爺,混跡於後臺,大數據,人工智能領域的小菜鳥。
更多請關注
file面試

相關文章
相關標籤/搜索