Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Given linked list -- head = [4,5,1,9], which looks like following:
4 -> 5 -> 1 -> 9
Example 1:
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list
should become 4 -> 1 -> 9 after calling your function.
Example 2:
Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list
should become 4 -> 5 -> 9 after calling your function.
public void deleteNode(ListNode node) {
node.val = node.next.val;
node.next=node.next.next;
}
这个题目比较简单,但是思路是不同于以往的,以往的思路总是想找到要删除的节点的前一个,删除节点,实际上在有一些情况,我们可以删除后一个,可以达到同样的目的。
Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
这是链表的最基础的题目,技巧就是采用一个虚拟头结点,可以方便的处理头结点的情况。
public ListNode removeElements(ListNode head, int val) {
ListNode tempNode =new ListNode(0);
tempNode.next = head;
ListNode cur =tempNode ;
while (cur.next != null){
if(cur.next.val == val){
cur.next = cur.next.next;
}else
cur = cur.next;
}
return tempNode.next;
}
涉及到对链表的正中间的节点的节点的处理,首先要想到用快慢指针的思路来解决,实际上,链表中用到快慢指针的地方有很多,例如判断链表是否有环等。
public ListNode removeMidNode(ListNode head) {
if (head == null || head.next == null) return head;
if (head.next.next == null ) return head.next;
ListNode dunny = new ListNode(0);
dunny.next = head;
ListNode slow = dunny;
ListNode fast = head.next;
while (fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
}
slow.next = slow.next.next;
return head;
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。