您的位置:首页 > Web前端

剑指offer_13(在O(1)的时间内删除链表中的某一个元素)

2017-03-17 16:32 330 查看
题意:在O(1)的时间内删除链表中的某一个元素

思路:若链表只有一个元素,那么就是删除这一唯一元素;若删除的是链表最后一个元素,那么只能从头遍历;若删除的是只是中间的一个元素,那么将待删除的元素的下一个元素的值赋给待删除元素,再将待删除元素的下一个元素给删除即可。

代码:

package MianShiTi_13;

import java.awt.List;

public class MianShiTi_13 {
public static class ListNode {
int value;
ListNode next;
}
public static ListNode deleteNode(ListNode head , ListNode toBeDeleted){
if(head == null || toBeDeleted == null){
return head;
}
if(head == toBeDeleted){
return head.next;
}
if(toBeDeleted.next == null){
ListNode tmp = head;
while (tmp.next != toBeDeleted) {
tmp = tmp.next;
}
tmp.next = null;
}
else{
toBeDeleted.value = toBeDeleted.next.value;
toBeDeleted.next = toBeDeleted.next.next;
}
return head;
}

public static void printListValue(ListNode head) {
while (head != null) {
System.out.print(head.value+" ");
head = head.next;
}
}

public static void main(String[] args) {
ListNode head = new ListNode();
head.value = 1;
head.next = new ListNode();
head.next.value = 2;
ListNode middle = head.next.next = new ListNode();
head.next.next.value = 3;
head.next.next.next = new ListNode();
head.next.next.next.value = 4;
ListNode last = head.next.next.next.next = new ListNode();
head.next.next.next.next.value = 5;

//删除节点为空
head = deleteNode(head, null);
printListValue(head);
System.out.println();

//删除中间节点
head = deleteNode(head, middle);
printListValue(head);
System.out.println();

//删除末尾节点
head = deleteNode(head, last);
printListValue(head);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: