本篇文章主要介绍了"链表-Remove Nth Node From End of List(删除指定的节点)",主要涉及到remove,node方面的内容,对于Javajrs看球网直播吧_低调看直播体育app软件下载_低调看体育直播感兴趣的同学可以参考一下:
问题描述:Given a linked list, remove the nth node from the end of list and return it...
问题描述:
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-1,也就是前面那个指针先跑n步,随后一起向后走,那么前面那个指针先跑到尾节点的时候,后面那个指针就指向被指定删除节点的前一个节点,把这个节点的next引用指向后面的后面的话就算完成了。
代码(java):
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null){
return null;
}
ListNode front = head;
ListNode back = head;
for(int i = 0 ; i < n ; i++){
front = front.next;
}
if(front == null)
{
head = head.next;
front = null;
return head;
}
while(front.next != null){
front = front.next;
back = back.next;
}
back.next = back.next.next;
return head;
}
}
以上就介绍了链表-Remove Nth Node From End of List(删除指定的节点),包括了remove,node方面的内容,希望对Javajrs看球网直播吧_低调看直播体育app软件下载_低调看体育直播有兴趣的朋友有所帮助。
本文网址链接:http://www.codes51.com/article/detail_1437829.html