剑指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); } }
相关文章推荐
- 剑指offer--面试题13:在O(1)时间删除链表节点
- 剑指offer面试题13-在O(1)时间删除链表的节点
- 【剑指offer】链表相关-在o(1)时间删除链表结点13
- 剑指offer13:O(1)时间删除链表节点
- 剑指offer 13. 在O(1)时间删除链表节点
- 【剑指offer】面试题13、在 O(1)时间上删除链表结点
- [剑指offer][面试题13]在O(1)时间删除链表结点
- 剑指offer-面试题13-在O(1)时间删除链表结点
- 剑指offer--面试题13:在O(1)时间删除链表结点--Java实现
- 剑指offer--面试题13:在O(1)时间删除链表结点
- 剑指offer--面试题13:在O(1)时间删除链表结点--Java实现
- 【剑指offer-Java版】13O(1)时间删除链表结点
- 剑指offer13:在O(1)时间删除链表结点
- 剑指Offer之在O(1)时间删除链表节点(题13)
- 剑指offer-面试题13-在O(1)时间删除链表节点
- 剑指Offer面试题13(java版):在O(1)时间删除链表节点
- 【剑指offer 面试题13】在 O(1) 时间删除链表结点
- 剑指offer之面试题13在O(1)时间删除链表结点
- 剑指offer-面试题 13:在 O( 1)时间删除链表结点
- 剑指Offer-13-在O(1)时间删除链表结点