给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2. 当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
package com.zb.www;
public class RemoveNthFromEnd {
public static void main(String[] args) {
// TODO Auto-generated method stub
ListNode head = new ListNode(1);
// head.next = new ListNode(2);
// head.next.next = new ListNode(3);
// head.next.next.next = new ListNode(4);
outPri(head);
removeNthFromEnd(head,1);
outPri(head);
}
public static ListNode removeNthFromEnd(ListNode head, int n) {
ListNode h = head;
ListNode hh = head;
//根据观察 通过一次遍历列表之后 再按顺序进行加法, 加到等于0时,则为要删除节点的前一个节点。
while(h != null){
h = h.next;
n--;
}
if(n==0){//删除的节点为头结点
head = head.next;
return head;
}
if(n<0){
while(++n!=0){
hh = hh.next;
}
hh.next = hh.next.next;
}
return head;
}
ListNode removeNthFromEnd1(ListNode head, int n) {//网上的另外一种写法 拓展一下思路 ,不过上面的写法参考左神的书 是最优解
// write your code here
ListNode p=head;
ListNode q=head;
for(int i=0;i<n;i++){
p=p.next;
}
if(p==null){
head=head.next;
return head;
}
while(p.next!=null){
p=p.next;
q=q.next;
}
q.next=q.next.next;
return head;
}
public static void outPri(ListNode head){
while(head != null){
System.out.print(head.val);
head = head.next;
}
System.out.println();
}
}