赞
踩
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
- /**
- * Definition for singly-linked list.
- * public class ListNode {
- * int val;
- * ListNode next;
- * ListNode(int x) { val = x; }
- * }
- */
- class Solution {
- public ListNode removeNthFromEnd(ListNode head, int n) {
- if(head==null||n==0){
- return null;
- }
- int i=0;
- ListNode f=head;
- ListNode s=head;
- ListNode p=head;
- //快节点先走n-1步
- while(f.next!=null&&i<n-1){
- f=f.next;
- i++;
- }
- //如果当前快节点到头了但是还没走到n-1步,说明链表长度不够,直接返回
- if(f.next==null&&i<n-1){
- return head;
- }
- //如果当前快节点到头了并且走到n-1步,说明删除链表头结点,返回head.next
- if(f.next==null&&i==n-1){
- return head.next;
- }
- //此时快慢同时出发,到快节点到头为止
- while(f.next!=null){
- f=f.next;
- //p记录s的前置节点
- p=s;
- s=s.next;
- }
- //删除s
- p.next=s.next;
- return head;
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。