题目可以在LeetCode查看
1. 删除链表的结点
用时:0ms
class Solution {
public void deleteNode(ListNode node) {
node.val=node.next.val;
node.next=node.next.next;
}
}
2. 删除链表的倒数第N个节点
用时:10ms
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode curNode=head;
ListNode nNode=head;
int count=1;
while(curNode.next!=null){
// 如果删除末尾结点,则判断当前结点是否是倒数第二个结点
if(n==1&&curNode.next.next==null){
curNode.next=null;
return head;
}
// 如果和当前结点中间的结点数为n,则移动nNode
if(count==n){
nNode=nNode.next;
}else{
++count;
}
curNode=curNode.next;
}
// 如果只有一个结点
if(nNode==head&&n==1){
return null;
}
// 删除该结点
nNode.val=nNode.next.val;
nNode.next=nNode.next.next;
return head;
}
}
3. 反转链表
用时:0ms
class Solution {
public ListNode reverseList(ListNode head) {