您的位置:首页 > Web前端 > Node.js

Remove Nth Node From End of List(链表,带测试代码)

2014-11-06 15:51 309 查看
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.首先回顾一下链表的基本特性,从三点来分析下:

1> 存储分配方式,链表用一组任意的存储单元存放线性表的元素。

2>时间性能,查找O(n),插入和删除,找出某位置指针后,插入和删除时仅为O(1)。

3>空间性能,不需要分配存储空间,只要需要就可以malloc,所以也叫动态链表。

4> 插入和删除节点图示:



2.动态链表的创建(leedcode的链表是没有头结点),第一个形参参数是指针,要想改变指针的值,需要用引用或者指向指针的指针。

void CreateListHead(ListNode* &head, int n)
{
int j=0;
head = (ListNode*)malloc(sizeof(ListNode));
head->next=NULL;
head->val=v[j++];//v是用户输入的每个节点的val
ListNode* p=head;
for (int i=1;i<n;++i)
{
ListNode* newNode;
newNode = (ListNode*)malloc(sizeof(ListNode));
p->next=newNode;
newNode->next=NULL;
newNode->val=v[j++];
p=p->next;
}
}


3.所有调试代码

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
int getLength(ListNode *head){
int length=0;
while(head){
++length;
head=head->next;
}
return length;
}
void deleteNode(ListNode* &head,int loc)//第一个位置是1
{
if(loc==1){
head=head->next;
}
else
{
ListNode* p=head;
int j=1;
while (p->next&&j<loc-1)
{
p=p->next;
++j;
}
p->next=p->next->next;
}
}
ListNode *removeNthFromEnd(ListNode *head, int n) {
if(head==NULL)
return NULL;
ListNode* res=head;//需要新建局部变量
int len=getLength(res);
int loc=len-n+1;
deleteNode(res,loc);
return res;
}
};
vector<int> v;
int num;
void CreateListHead(ListNode* &head, int n)
{
int j=0;
head = (ListNode*)malloc(sizeof(ListNode));
head->next=NULL;
head->val=v[j++];
ListNode* p=head;
for (int i=1;i<n;++i)
{
ListNode* newNode;
newNode = (ListNode*)malloc(sizeof(ListNode));
p->next=newNode;
newNode->next=NULL;
newNode->val=v[j++];
p=p->next;
}
}
int main()
{
freopen("C:\\Users\\Administrator\\Desktop\\test.txt","r",stdin);
cin>>num;
for (int i=0;i<num;++i)
{
int temp;
cin>>temp;
v.push_back(temp);
}
ListNode* head=NULL;
CreateListHead(head,num);
Solution so;
ListNode* res=so.removeNthFromEnd(head,1);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐