Remove Nth Node From End of List
来源:互联网 发布:c语言输出心形图案 编辑:程序博客网 时间:2024/06/05 19:45
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.
题目解析:
(1)保持两个指针,让他们相差n就可以了
(2)主要是边界问题
1、{1},1的情况下,处理的时候,我们当
k>=0的时候也就是要删除第一个元素,比较特殊,因此得特别对待。
#include <iostream>using namespace std;struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {}};ListNode *removeNthFromEnd(ListNode *head, int n) {ListNode *p = head;int k = n-1;while(p->next!=NULL && k>=0){p = p->next;k--;}if(k>=0){head = head->next;return head;}ListNode *q = head;while(p->next!=NULL){p = p->next;q = q->next;}q->next = q->next->next;return head;}int main(void){ListNode *head;ListNode *node = (ListNode *)malloc(sizeof(ListNode));node->val = 1;node->next = NULL;head = node;removeNthFromEnd(head, 1);system("pause");return 0;}
0 0
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node from End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- mac c cpp
- 一个十分简单的div弹出层小例子
- Unicode和UTF-8的关系
- 泛洪攻击的几种方法解析
- SSH面试题整理
- Remove Nth Node From End of List
- VIJOS P1908合唱队形
- leetcode面试题3:Max Points on a Line
- 集群中几种session同步解决方案的比较
- POJ 1704 Georgia and Bob(nim博弈论)
- 科学计算器(可实现带括号的浮点数四则运算)
- VIJOS P1777引水入城
- xmemcached的缓存更新机制
- zoj 2822 - Sum of Different Primes