题目及测试
package sword013;
/*问题描述:给定单向链表的头指针和一个结点指针,定义一个函数在O(1)时间删除该结点。
*/
public class main {
public static void main(String[] args) {
LinkList a=new LinkList(1);
a.addLast(2);
a.addLast(5);
a.printList();
test(a.first,a.first.next.next);
}
private static void test(ListNode ito,ListNode ito2) {
Solution solution = new Solution();
ListNode rtn;
long begin = System.currentTimeMillis();
System.out.println();
//开始时打印数组
rtn=solution.deleteNode(ito,ito2);//执行程序
long end = System.currentTimeMillis();
rtn.printNodeToEnd();
//System.out.println(":rtn" );
//System.out.print(rtn);
System.out.println();
System.out.println("耗时:" + (end - begin) + "ms");
System.out.println("-------------------");
}
}
解法1(成功)
如果删除节点是头结点,返回头结点的next
如果删除节点是中间结点,删除节点的值设置为next的值,然后删除节点的next指向next的next
如果删除节点是尾节点,从头开始遍历,设置删除节点的前一个节点的next为null
package sword013;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteNode(ListNode head, ListNode deListNode) {
if(head == null) {
return null;
}
if(head == deListNode) {
ListNode next = head.next;
head.next = null;
return next;
}
// 删除最后一个节点
if(deListNode.next == null) {
ListNode now =head;
while(now.next != deListNode) {
now = now.next;
}
now.next = null;
}
// 删除中间节点
else {
ListNode next = deListNode.next;
deListNode.val = next.val;
deListNode.next = next.next;
next.next = null;
}
return head;
}
}