lintcode-easy-Delete Node in the Middle of Singly Linked List

Implement an algorithm to delete a node in the middle of a singly linked list, given only access to that node.

Example

Given 1->2->3->4, and node 3. return 1->2->4

 

删除的方法就是用后面的值覆盖前面的值,注意避免OBOB

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param node: the node in the list should be deleted
     * @return: nothing
     */
    public void deleteNode(ListNode node) {
        // write your code here
        ListNode p = node;
        
        while(p.next.next != null){
            p.val = p.next.val;
            p = p.next;
        }
        p.val = p.next.val;
        p.next = null;
        
        return;
    }
}

 

posted @ 2016-02-24 17:43  哥布林工程师  阅读(117)  评论(0编辑  收藏  举报