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

leetcode 19. Remove Nth Node From End of List

2016-06-09 20:47 441 查看
先遍历统计链表长度count,要删除的就是从前往后的第count-n+1个节点,只需要找到第count-n个节点,用pointer->next=pointer->next->next删除节点。另外添加对一些特殊情况的处理:只有1个节点和count==n。

包括main函数以及添加节点函数的源代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>

struct ListNode* add(struct ListNode* l1,int num);
struct ListNode* removeNthFromEnd(struct ListNode* head, int n);
struct ListNode {
int val;
struct ListNode *next;
};

int main()
{
struct ListNode *result=NULL;
struct ListNode *l1=NULL;
struct ListNode *l2=NULL;
l1=add(l1,1);
add(l1,2);
// add(l1,3);
print(l1);
//result=addTwoNumbers()
l1=removeNthFromEnd(l1,2);
print(l1);
return 0;
}

struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
struct ListNode* pointer=head;
int i,count;
i=0;
count=0;
if(pointer->next==NULL&&n==1)
return NULL;
while(pointer!=NULL)
{
pointer=pointer->next;
count++;
}
pointer=head;
if(n==count)
{
head=head->next;
return head;
}
while(pointer->next!=NULL)
{
if(i==count-n-1)
break;
pointer=pointer->next;
i++;
}
pointer->next=pointer->next->next;
return head;
}

int print(struct listNode* l1)
{
struct ListNode* pointer;
pointer=l1;
while(pointer!=NULL)
{
printf("%d ",pointer->val);
pointer=pointer->next;
}
return 0;
}
struct ListNode* add(struct ListNode* l1,int num)
{
struct ListNode* pointer;
struct ListNode* newNode;
pointer=l1;
if(l1==NULL)
{
newNode=(struct ListNode*)malloc(sizeof(struct ListNode));
newNode->val=num;
newNode->next=NULL;
l1=newNode;
}
else
{
while(pointer->next!=NULL)
pointer=pointer->next;
newNode=(struct ListNode*)malloc(sizeof(struct ListNode));
newNode->val=num;
newNode->next=NULL;
pointer->next=newNode;
}

return l1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: