13、在O(1)时间删除链表节点

来源:互联网 发布:p图很萌的软件 编辑:程序博客网 时间:2024/06/06 00:42
package test;class ListNode{int val;ListNode next;public ListNode(int x){val = x;}}public class Solution {public ListNode deleteNode(ListNode head, ListNode target){if(head == null) return head;ListNode h = new ListNode(0);h.next = head;ListNode p = h;while(p.next != null){if(p.next == target){p.next = p.next.next;return h.next;}p = p.next;}return h.next;}public static void main(String args[]){ListNode l1 = new ListNode(0);ListNode l2 = new ListNode(1);ListNode l3 = new ListNode(2);l1.next = l2;//l2.next = l3;Solution sl = new Solution();System.out.println(sl.deleteNode(l1,l2));}}