题目描述
给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
示例:
输入:head = [1,2,3,4,5], n = 2 输出:[1,2,3,5]
输入:head = [1], n = 1 输出:[]
输入:head = [1,2], n = 1 输出:[1]
题目分析
本题相对来说比较简单,可以先编写方法获取链表的长度(legnth)
题目就变为删除链表的第length-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 node = new ListNode(0,head);
int length = getLength(head);
ListNode current = node;
for(int i = 0; i < length - n; i++){
current = current.next;
}
//删除操作
current.next = current.next.next;
return node.next;
}
public int getLength(ListNode head){
int length = 0;
while(head != null){
++length;
head = head.next;
}
return length;
}
}