leetCode 19. Remove Nth Node From End of List 链表

简介:

19. 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.

题目大意:

找到链表中倒数第N个元素,删除这个元素。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
  * Definition for singly-linked list.
  * struct ListNode {
  *     int val;
  *     ListNode *next;
  *     ListNode(int x) : val(x), next(NULL) {}
  * };
  */
class  Solution {
public :
     int  lengthOfList(ListNode* head)
     {
         int  i = 0 ;
         while (head != NULL)
         {
             i++;
             head = head->next;
         }
         return  i;
     }
     ListNode* removeNthFromEnd(ListNode* head,  int  n) {
         if (head == NULL)
             return  NULL;
         ListNode* p = head;
         int  pre = lengthOfList(head) - n ;
         if (pre == 0)
             return  head->next;
         cout << pre<< "  " <<lengthOfList(head)<<endl;
         while (--pre)
             p = p->next;
         p->next = p->next->next;
         return  head;
     }
};



本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1837285
相关文章
|
11月前
【力扣】-- 移除链表元素
【力扣】-- 移除链表元素
117 1
|
11月前
Leetcode第21题(合并两个有序链表)
这篇文章介绍了如何使用非递归和递归方法解决LeetCode第21题,即合并两个有序链表的问题。
145 0
Leetcode第21题(合并两个有序链表)
|
5月前
|
算法 Go
【LeetCode 热题100】23:合并 K 个升序链表(详细解析)(Go语言版)
本文详细解析了 LeetCode 热题 23——合并 K 个升序链表的两种解法:优先队列(最小堆)和分治合并。题目要求将多个已排序链表合并为一个升序链表。最小堆方法通过维护节点优先级快速选择最小值,;分治合并则采用归并思想两两合并链表。文章提供了 Go 语言实现代码,并对比分析两种方法的适用场景,帮助读者深入理解链表操作与算法设计。
171 10
|
11月前
LeetCode第二十四题(两两交换链表中的节点)
这篇文章介绍了LeetCode第24题的解法,即如何通过使用三个指针(preNode, curNode, curNextNode)来两两交换链表中的节点,并提供了详细的代码实现。
116 0
LeetCode第二十四题(两两交换链表中的节点)
|
11月前
Leetcode第十九题(删除链表的倒数第N个节点)
LeetCode第19题要求删除链表的倒数第N个节点,可以通过快慢指针法在一次遍历中实现。
111 0
Leetcode第十九题(删除链表的倒数第N个节点)
|
11月前
|
索引
力扣(LeetCode)数据结构练习题(3)------链表
力扣(LeetCode)数据结构练习题(3)------链表
227 0
|
11月前
【LeetCode 10】142. 环形链表 II
【LeetCode 10】142. 环形链表 II
78 0
|
11月前
【LeetCode 09】19 删除链表的倒数第 N 个结点
【LeetCode 09】19 删除链表的倒数第 N 个结点
130 0
|
11月前
【LeetCode 08】206 反转链表
【LeetCode 08】206 反转链表
56 0
|
11月前
【LeetCode 06】203.移除链表元素
【LeetCode 06】203.移除链表元素
81 0