• linkedlist 常见api: 取中点, 翻转, 合并,插入


    取中点:

    1   ListNode fast = head , slow = head ;
    2         ListNode mid = null ;
    3         //step 1: find the middle node: when fast reaches the end, slow reaches the mid
    4         //note: middle node has to be fast.next != null && fast.next.next != null
    5         while (fast != null && fast.next != null && fast.next.next != null){
    6             fast = fast.next.next ;
    7             slow = slow.next ;
    8         }
    9         mid = slow ;

     

    翻转:

     1 /*1->2->3->4   to 1<-2<-3<-4
     2     *                          p c
     3     * */
     4     private ListNode reverse(ListNode head){
     5         ListNode pre = null ;
     6         ListNode curr = head ;
     7         while (curr!= null){
     8             ListNode temp = curr.next ;
     9             curr.next = pre ;
    10             pre = curr ;
    11             curr = temp;
    12         }
    13         return pre ;
    14     }

     

    合并:

     1 private ListNode merge(ListNode head1, ListNode head2) {
     2     ListNode curr1 = head1, curr2 = head2, temp1 = null, temp2 = null;
     3    while (curr1.next != null && curr2 != null) {
     4    temp1 = curr1.next;
     5       temp2 = curr2.next;
     6       curr1.next = curr2;
     7       curr2.next = temp1;
     8       curr1 = temp1;
     9       curr2 = temp2;
    10     }
    11     if (curr2 != null) {
    12      curr1.next = curr2;
    13       curr2.next = null;
    14     }
    15     else {
    16      curr1.next = null;
    17     }
    18     return head1;
    19   }

     

    插入:使用DUMMY head 避免了头部不确定, 头部为空等各种情况

     1 public ListNode insert(ListNode head, int value) {
     2         // Write your solution here
     3         ListNode dummy = new ListNode(0);
     4         dummy.next = head ;
     5         ListNode pre = dummy ;
     6         ListNode curr = head ;
     7         while (curr != null && curr.val<=value){
     8             pre = curr ;
     9             curr = curr.next ;
    10         }
    11         ListNode target = new ListNode(value) ;
    12         pre.next = target ;
    13         target.next = curr ;
    14         //work for both cases: before head or in the middle
    15         return dummy.next ;
    16     }
  • 相关阅读:
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    Orge 安装
    vs番茄插件卸载,安装,破解
    Orge 学习资源
    3d开源引擎收集
    hashtable遍历
    java synchronized
    java 调用 ant
    用Ant实现Java项目的自动构建和部署
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8469073.html
Copyright © 2020-2023  润新知