/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void run(ListNode*head, int &num)//遍历链表,得到链表的长度;
{
while (head != NULL)
{
num++;
head = head->next;
}
}
ListNode* removeNthFromEnd(ListNode* head, int n) {
int num=0;
if (head == NULL)
return NULL;
run(head, num);
if (n > num)
cout << "删除位置不合法";
else
{
ListNode*p = NULL,*q=NULL;
int i = 1;
if (n == num)//删除首结点;
{
q = head;
head = head->next;
delete q;
}
else//删除的不是首结点
{
q = head->next;
p = head;
while (i < num-n)
{
p = q;
q = q->next;
i++;
}
p->next = q->next;
delete q;
}
return head;
}
}
};
当前题目:RemoveNthNodeFromEndofList
网页网址:
http://cdxtjz.cn/article/pisjcj.html