<span style="font-family: Arial, Helvetica, sans-serif; font-size: 18px; background-color: rgb(255, 255, 255);">先看这样一道题:</span>
Delete Node in a Linked List
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4
and you are given the third node with value 3
, the linked list should become 1 -> 2 -> 4
after calling your function.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public void deleteNode(ListNode node) {
if(node==null)
return;
node.val = node.next.val;
node.next = node.next.next;
}
}
注意这里我们并不是真的删除了3的那个节点(已题为例),只是将3的那个节点的知道换成下一个节点的值,然后把3这个节点的指针指向下一个节点的下一个节点(因为4那个节点我们放到3哪里了)
再看这题
Remove Duplicates from Sorted List II
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
<span style="font-size:14px;">/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null)
return null;
ListNode fakehead = new ListNode(-1);
fakehead.next = head;
ListNode p = fakehead,p1 = head;
int flag = 0;
while(p1!=null&&p1.next!=null){
if(p1.val==p1.next.val){
p1 = p1.next;
flag = 1;
}
else{
if(flag==0){
p = p.next;
p1 = p.next;
}
else{
p.next = p1.next;
flag = 0;
p1 = p.next;
}
}
}
/*if we need to delete the last node,like this 1->2->3->3->3.
we need to add below code
*/
if(flag==1){
p.next = p1.next;
}
return fakehead.next;
}
}</span><span style="font-size: 24px;">
</span>