❤ 作者主页:李奕赫揍小邰的博客
❀ 个人介绍:大家好,我是李奕赫!( ̄▽ ̄)~*
🍊 记得点赞、收藏、评论⭐️⭐️⭐️
📣 认真学习!!!🎉🎉
文章目录
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
解法一:双指针
双指针就是两个指针,first和second两个指针,first一直领先second有n个长度,因此对于本体当first为空时,second正好处于倒数第n个位置,second.next=second.next.next直接删除第n个。
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode p=new ListNode(0,head);
ListNode first=head;
ListNode second=p;
for(int i=0;i<n;i++)
first=first.next;
while(first!=null){
first=first.next;
second=second.next;
}
second.next=second.next.next;
ListNode p1=p;
return p1.next;
}
解法二:直接计算链表长度
计算链表长度,然后遍历到倒数第n为,然后cur.next=cur.next.next,就可以删除第n个结点。
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head);
int length = getLength(head);
ListNode cur = dummy;
for (int i = 1; i < length - n + 1; ++i) {
cur = cur.next;
}
cur.next = cur.next.next;
ListNode ans = dummy.next;
return ans;
}
public int getLength(ListNode head) {
int length = 0;
while (head != null) {
++length;
head = head.next;
}
return length;
}