19. 删除链表的倒数第N个节点

给定一个链表,删除链表的倒数第 个节点,并且返回链表的头结点。

示例:

给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后,链表变为 1->2->3->5.

说明:

给定的 n 保证是有效的。

进阶:

你能尝试使用一趟扫描实现吗?


package leetCode_5_8;
/** 
* @author : caoguotao
* @date 创建时间:2019年5月11日 下午8:33:11 
* @version 1.0 
* @parameter  
* @since  
* @return  
*/
public class Solution19 {

	public static void main(String[] args) {
		ListNode node1 = new ListNode(1);
		ListNode node2 = new ListNode(2);
		node1.next = node2;
		ListNode node3 = new ListNode(3);
		node2.next = node3;
		ListNode node4 = new ListNode(4);
		node3.next = node4;
		ListNode node5 = new ListNode(5);
		node4.next = node5;
		node5.next = null;
		ListNode head = removeNthFromEnd(node1, 1);
		while(head != null) {
			System.out.println(head.data);
			head = head.next;
		}
	}
	 public static ListNode removeNthFromEnd(ListNode head, int n) {
	       ListNode temp = new ListNode(0);
	       temp.next = head;
	       ListNode rear = temp, nthNode = temp;
			if(n < 1)
				System.out.println("n的输入有误");
			for(int i = 0; i < n; i++) {
	            rear = rear.next; 
			}
			while(rear != null && rear.next != null) {
				rear = rear.next;
				nthNode = nthNode.next;
			}
			nthNode.next = nthNode.next.next;
			return temp.next; 
		}
}
class ListNode{
	int data;
	ListNode next;
	public ListNode(int data) {
		super();
		this.data = data;
	}

	public ListNode(int data, ListNode next) {
		super();
		this.data = data;
		this.next = next;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值