标签:else move 位置 rom src 链表 节点 from head
通过两次扫描实现。ToDo:用一趟扫描实现
/**
* 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) {
int length = 0;
int pos;
int count = 0;
if(head == null){
return null;
}
ListNode curNode = head;
//获取链表长度
while(curNode != null){
length++;
curNode = curNode.next;
}
//正序位置,从0开始计数
pos = length - n;
if(pos == 0){
return head.next;
}
curNode = head;
while(true){
count++;
if(count != pos){
curNode = curNode.next;
}else{
curNode.next = curNode.next.next;
break;
}
}
return head;
}
}
标签:else move 位置 rom src 链表 节点 from head
原文地址:https://www.cnblogs.com/WillamZ/p/11478806.html