算法内容
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
进阶:你能尝试使用一趟扫描实现吗?
示例1:
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1
输出:[]
示例 3:
输入:head = [1,2], n = 1
输出:[1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
算法思想
该算法在学《数据结构与算法》这一门课程时,都会接触到这一算法,这里我们依然用图来简单的介绍一下该算法思想:
- 普通链表(链表长度>n)
- 特殊状态(算法长度=n)
整体算法
public class Day_17 {
static Scanner input=new Scanner(System.in);
public static ListNode removeNthFromEnd(ListNode head, int n) {
ListNode after=head;
ListNode first=head;
ListNode changes=head;
for (int i = 0; i < n-1; i++) {
after=after.next;
}
if (after.next==null){
return first.next;
}
while (after.next!=null){
changes=first;
after=after.next;
first=first.next;
}
changes.next=first.next;
return head;
}
public static ListNode input_link_test(int n, ListNode head){
ListNode temp=head;
for (int i = 0; i < n-1; i++) {
int num =input.nextInt();
ListNode listNode=new ListNode(num,null);
temp.next=listNode;
temp=temp.next;
}
return head;
}
public static void main(String[] args) {
System.out.print("输入单链表长度n:");
int n=input.nextInt();
System.out.println("----------------------------------------------------------");
System.out.print("输入删除倒数第几个数字:");
int num_count=input.nextInt();
System.out.println("-----------------------------------------------------------");
System.out.println("输入测试数字:");
int num =input.nextInt();
ListNode head=new ListNode(num,null);
input_link_test(n,head);
System.out.println("-----------------------------------------------------------");
head=removeNthFromEnd(head,num_count);
while (head!=null){
System.out.println(head.val);
head=head.next;
}
}
}
尾语
以上属于个人见解,有好的想法可以在下方评论写出自己的想法,大家一起进步。该题是力扣上的题,若有侵权,请及时告知。该题链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list