19. 删除链表的倒数第N个结点
题目:


题解:
java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null) {
return head;
}
ListNode cur = head;
int length = 0;
while(cur != null) {
cur = cur.next;
length++;
}
n = length-n;
cur = head;
if(n==0) {
return head.next;
}
length = 0;
while(cur != null) {
length++;
if(length==n) {
cur.next = cur.next.next;
}
cur = cur.next;
}
return head;
}
}
82. 删除排序链表的重复元素Ⅱ
题目:


题解:
java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null) {
return head;
}
//指向当前元素
ListNode cur = head;
//创建虚拟头节点
ListNode drum = new ListNode();
drum.next = head;
//用一个pre指向当前元素的前面一个指针
ListNode pre = drum;
while(cur.next != null) {
if(pre.next.val != cur.next.val) {
cur = cur.next;
pre = pre.next;
}
else {
while(cur.next != null && pre.next.val == cur.next.val) {
cur = cur.next;
}
cur = cur.next;
pre.next = cur;
}
//这里进行判断cur!=null是因为cur可能经过else之后变成null,cur.next就会报空指针异常
//如果把这个放在while里面进行判断,那么下面的出了while以后的if,else就会报错,因为进行了cur=cur.next
if(cur == null) {
return drum.next;
}
}
if(pre.next == cur) {
cur = cur.next;
}
else {
pre.next = cur.next;
}
return drum.next;
}
}