算法 - 链表操做题目套路

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面试

相关文章
相关标签/搜索