参考derrantcm的博客,网址:https://blog.csdn.net/derrantcm/article/details/46905467
package algorithm;
import java.util.LinkedList;
import java.util.List;
/*
移除单链表的倒数第N个节点
原题
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
题目大意
删除单链表的倒数第N个结点,注意:输入的N都是合法,在一次遍历中完成操作。
解题思路
先让一个指针走找到第N个节点,然后再让一个指针指向头结点,然后两具指针一起走,直到前一个指针直到了末尾,后一个指针就是倒数第N+1个结点,删除倒数第N个结点就可以了。
*/
public class RemoveNthNumFromEnd {
static class Node{
int value;
Node nextNode;
public Node(int value){
this.value=value;
this.nextNode=null;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getNextNode() {
return nextNode;
}
public void setNextNode(Node nextNode) {
this.nextNode = nextNode;
}
}
public static Node makeListNode(int[] nums){
Node listNode=null;
Node pre=null;
for(int i=0;i<nums.length;i++){
Node node=new Node(nums[i]);
if(listNode==null){
listNode=node;
pre=node;
}else{
pre.nextNode=node;
pre=pre.nextNode;
}
}
return listNode;
}
public static void printList(Node listNode){
if(listNode==null)
return;
System.out.println();
int value=listNode.getValue();
System.out.print(value);
Node node=listNode.getNextNode();
while(node!=null){
value=node.getValue();
System.out.print(","+value);
node=node.getNextNode();
}
System.out.println();
}
public static int getNodeListCount(Node listNode){
if(listNode==null)
return 0;
int result=1;
Node node=listNode.getNextNode();
while(node!=null){
node=node.getNextNode();
result++;
}
return result;
}
//删除倒数第n个数
public static Node removeNthFromEnd(Node node,int n){
if(node==null){
return null;
}
int count=getNodeListCount(node);
System.out.println("Node的数量="+count);
int deleteNum=count-n+1; //需要删除的第几个元素
Node pa=node;
Node pb=node;
//遍历第几个数
for(int i=0;i<deleteNum-2&&pa!=null;i++){
pa=pa.nextNode;
}
System.out.println(deleteNum);
if(deleteNum==1){
//删除第一个节点
pa=pa.nextNode;
return pa;
}else if(deleteNum>1){
//删除该节点
pa.nextNode=pa.nextNode.nextNode;
return node;
}else{
}
return pa;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] nums={1,2,3,4,5};
Node node=makeListNode(nums);
printList(node);
Node node1=removeNthFromEnd(node,1);
//printList(node);//原始数据
printList(node1); //删除后数据
}
}