题目
https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6?tpId=188&&tqId=36726&rp=1&ru=/ta/job-code-high-week&qru=/ta/job-code-high-week/question-ranking
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode removeNthFromEnd (ListNode head, int n) {
// write code here
int count = 0;
ListNode root = head;
while(root!=null){
count++;
root = root.next;
}
int index = count - n + 1;
root = head;
if(index != 1){
while(root != null&& index<=count){
index--;
if(index == 1){
root.next = root.next.next;
break;
}
root = root.next;
}
return head;
}else{
return head.next;
}
}
}
全部评论
(0) 回帖