博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leecode 记录——Remove Nth Node From End of List
阅读量:4137 次
发布时间:2019-05-25

本文共 1278 字,大约阅读时间需要 4 分钟。

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.

很简单的一个用链表的实现,但是细节总是难以全部想到,想要一次完成没有错误的编程还需要联系。

一开始,不知道怎么用one pass完成,就写了个脑残的。

struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {

struct ListNode* first = (struct ListNode*)malloc(sizeof(struct ListNode));//leecode中的链表没有不包含数据的头指针!自己模拟一个
first->next = head;
struct ListNode* temp = first;
int i, N;
for (i = 0; temp->next != NULL; i++)
{
temp = temp->next;
}
N = i - n + 1;
if (N == 1 && n == 1)//如果链表长度为1,返回NULL
{
return NULL;
}
else{
temp = first;
for (i = 1; i < N; i++)
{
temp = temp->next;
}
temp->next = temp->next->next;
}
return first->next;//因为可能删除第一个节点

}

百度了一下,找到one pass的方法,使用双指针。以前听过怎么快速定位到中间位置,设两个指针,一个跑一步,一个跑两步,但是没能够举一反三。

struct ListNode* first = (struct ListNode*)malloc(sizeof(struct ListNode));

first->next = head;
struct ListNode* temp1 = first;
struct ListNode* temp2 = first;
int i, N;
for (i = 0; i<n; i++)
{
temp2 = temp2->next;
}
while (temp2->next != NULL)
{
temp1 = temp1->next;
temp2 = temp2->next;
}
temp1->next = temp1->next->next;
return first->next;

转载地址:http://khovi.baihongyu.com/

你可能感兴趣的文章
第三方SDK:百度地图SDK的使用
查看>>
Android studio_迁移Eclipse项目到Android studio
查看>>
JavaScript setTimeout() clearTimeout() 方法
查看>>
CSS border 属性及用border画各种图形
查看>>
转载知乎-前端汇总资源
查看>>
JavaScript substr() 方法
查看>>
JavaScript slice() 方法
查看>>
JavaScript substring() 方法
查看>>
HTML 5 新的表单元素 datalist keygen output
查看>>
(转载)正确理解cookie和session机制原理
查看>>
jQuery ajax - ajax() 方法
查看>>
将有序数组转换为平衡二叉搜索树
查看>>
最长递增子序列
查看>>
从一列数中筛除尽可能少的数,使得从左往右看这些数是从小到大再从大到小...
查看>>
判断一个整数是否是回文数
查看>>
经典shell面试题整理
查看>>
腾讯的一道面试题—不用除法求数字乘积
查看>>
素数算法
查看>>
java多线程环境单例模式实现详解
查看>>
将一个数插入到有序的数列中,插入后的数列仍然有序
查看>>