题目描述
给定一个链表,删除链表的倒数第n个节点并返回链表的头指针
(欢迎大家批评指正,讨论好的方法)
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * * @param head ListNode类 * @param n int整型 * @return ListNode类 */ public ListNode removeNthFromEnd (ListNode head, int n) { int len = 0; ListNode p = head; ListNode reHead = head; while(p != null){ len++; p = p.next; } if(n == len){ reHead = head.next; head.next = null; return reHead; } int cha = len-n-1; ListNode temp = head; while(cha >0 ){ temp = temp.next; cha--; } temp.next = temp.next.next; return head; //这里回reHead 和head都可以,因为len不等于n时,head不变 } }
全部评论
(1) 回帖