其实这次没太看懂题目啊 那个函数输入的是要删除的节点还是头节点啊好郁闷 就当作删除的节点来写了没想到ok的?(小声 啊数据结构这玩意真的该复习一波了orz
Problem Description
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void deleteNode(ListNode* node) {
}
};
Note:
- The linked list will have at least two elements.
- All of the nodes’ values will be unique.
- The given node will not be the tail and it will always be a valid node of the linked list.
- Do not return anything from your function.
Solution
就 思路很简单,被删掉的那个节点的val就是它的next的val,它的next就变成了next->next
的那个点。然后注意链表至少含有两个元素,所以当小于两个时, 就不做任何操作直接返回。
class Solution {
public:
void deleteNode(ListNode* node) {
if(!node || !node->next) return;
ListNode *n = node->next;
node->val = n->val;
node->next = n->next;
}
};