Remove Nth Node From End of List
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.
解题思路:这道题比较容易,是一道链表操作题,首先进行遍历,记录下长度,然后再遍历,这时就可以删除指定的节点,此时的时间复杂度为O(N+M),这是最简单的一种做法,但是要考虑删除为头结点和尾节点这两种特殊情况。
代码如下:
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; } public ListNode removeNthFromEnd(ListNode head, int n) {
//删除链表倒数第n个结点 从1开始计数
ListNode temp = head;
int size =0;
while(temp.next!=null){
temp = temp.next;
size++;
}
if(size==0){//size从0开始计算
return null;
}
ListNode temp1 = head;
int t = size - n;
int index=0;
//若删除结点为第一个则如此操作
if(t==-1){
head = head.next;
return head;
}
while(temp1.next!=null){
if(index==t){
if(t==size-1){//若删除最后一个结点则如此操作
temp1.next=null;
break;
}
temp1.next = temp1.next.next;
}
temp1 = temp1.next;
index++;
}
return head;
}
}
当然,Accept之后从Discuss中发现,也有更加简易的做法,在这里学习两个:
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
static int depth = 0, levels = 0;
if (!head) {levels = depth++; return NULL;}
depth++;
head->next = removeNthFromEnd (head->next, n);
depth--;
if (levels - depth + 1 == n) return head->next;
return head;
}public ListNode RemoveNthFromEnd(ListNode head, int n) {
ListNode h1=head, h2=head;
while(n-->0) h2=h2.next;
if(h2==null)return head.next; // The head need to be removed, do it.
h2=h2.next;
while(h2!=null){
h1=h1.next;
h2=h2.next;
}
h1.next=h1.next.next; // the one after the h1 need to be removed
return head;
}人家都是one pass,leetcode真是高手如林。
本文详细介绍了如何使用链表操作解决删除链表倒数第n个节点的问题,包括基本思路和两种简化做法。文章还提供了代码实现,帮助读者理解并实践这一算法。
642

被折叠的 条评论
为什么被折叠?



