链表数据结构

2019-01-16  本文已影响0人  YOLO哈哈哈

链表数据结构

1· 删除链表的节点在O(1)时间内(18 剑指offer )
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public void deleteNode(ListNode toBeDeleted, ListNode root) {
       /* 要删除的链表不是尾节点 的O(1)情况*/
      if(toBeDeleted.next != null) {
          toBeDeleted.val = toBeDeleted.next.val;
          toBeDeleted.next = toBeDeleted.next.next;
      }
      else if( toBeDeleted == root){
    
          root = null;
      }
      else{ /* 要删除链表的尾部*/
          ListNode ptr = root;
          while( ptr.next != toBeDeleted ){
                ptr = ptr.next;
          }
           ptr.next = null;
      }
    }
}
2· 删除链表中重复的节点 (18 剑指offer )
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteDuplication(ListNode head) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode ptr = dummy; /*从dummy node 这里开始遍历,因为root 也是有可能被删的*/
        /* 这里不写*/
        while(ptr.next != null){
             ListNode pNext = ptr.next;
              while(pNext != null && ptr.next.val == pNext.val)
                    pNext ++;
              if( ptr.next.next == pNext)
                      ptr = ptr.next;
              else{
                  ptr.next = pNext;
              }      
         }/* while*/
     return dummy.next;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读