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

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

 

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

示例:
给定一个链表: 1->2->3->4->5, 和 n = 2. 当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:

你能尝试使用一趟扫描实现吗?
思路:首先循环判断有m个节点,根据倒数第n个数,得出第前 m-n个,接下来要做的是遍历获取前m-n个,为了做遍历,首先先判断第一个节点,如果为指定的节点k == 0,再next连接删除第n个节点后的节点(如果被删除后面还有节点)。
java的code

/**
 * 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 m = 0;
        ListNode temp = head;
        ListNode result = null;
        ListNode tempresult = null;
        while(temp != null) {
            temp = temp.next;
            m++;
        }
        
        int k = m - n;
        
        if(k != 0) {
        	result = new ListNode(head.val);
        	tempresult = result;
        	temp = head;
        	
        }else {
        	if(head.next != null){
        		result = new ListNode(head.next.val);
            	temp = head;
            	tempresult = result;
        	}else {
        		return null;
        	}
        	
        }
        
        for(int i= 1; i < k ; i++) {
        	temp = temp.next; 
        	tempresult.next = new ListNode(temp.val);
        	tempresult = tempresult.next;
        }
     
        
           temp = temp.next;
           System.out.println(temp.val);
        if(temp != null) {	
        
        	 tempresult.next = temp.next;
        	 
        }
       
        
//        while(result != null) {
//        	System.out.print(result.val + "  ");
//          result = result.next;
//        }
      return result;  
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值