19.Remove Nth Node From End of List
题目
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.
题意
给定一个链表,移除倒数第n个元素
注意
当给定的n超过链表的长度,n为负数。保证n的合法性
n的计数从0开始还是1开始,该题是从1开始
思路
- 这题的重点是倒数第n个元素的定为,从最后往前数等于n的位置是需要删除的
2.删除一个元素就要知道该元素的前一个元素。
3.当给定两个指针(start,end),区间内含有n个元素,当end指向NULL链表结尾,start指向元素的下一个元素就是倒数第n个元素,需要删除。
代码
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *virtualNode = new ListNode(0);
virtualNode->next = head;
ListNode *start = virtualNode;
ListNode *end = virtualNode;
n+=1;
while(n--) //区间[start,end]的元素个数很重要,区间内含所有n个元素
{
end=end->next;
}
while(end!=NULL)
{
start = start->next;
end = end->next;
}
//取next的时候需要知道是否有效
if(start)
{
ListNode *dele = start->next;
if(dele)
{
start->next = dele->next;
delete dele;
}
}
return virtualNode->next;
}
};
结果
237. Delete Node in a Linked List
题目
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.
题意
写一个函数,删除给定的结点
注意
注意这里并没有给链表的头结点,仅仅只给了需要删除的结点
尽管之前说不能给链表的结点赋值,但是这个题需要这样做
思路
给了删除的节点,删除结点之后的信息我们可以知道的。
将删除结点的下一个结点的值赋给删除结点的位置,并将删除结点的next域指向next的next。
代码
class Solution {
public:
void deleteNode(ListNode* node) {
//对结点的有效性进行判断
if(node == NULL)
{
return;
}
if(node->next == NULL)
{
node = NULL;
return;
}
node->val = node->next->val;
ListNode* dele = node->next;
node->next = dele->next;
delete dele;
}
};
结果
效率尽管底,进行了容错处理,真正删除内存