题目描述
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Given linked list – head = [4,5,1,9], which looks like following:
Example 1:
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/delete-node-in-a-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码
无前驱情况下的链表删除结点操作
#include <iostream>
#include <cassert>
using namespace std;
/// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/// LinkedList Test Helper Functions
ListNode* createLinkedList(int arr[], int n){
if(n == 0)
return NULL;
ListNode* head = new ListNode(arr[0]);
ListNode* curNode = head;
for(int i = 1 ; i < n ; i ++){
curNode->next = new ListNode(arr[i]);
curNode = curNode->next;
}
return head;
}
void printLinkedList(ListNode* head){
ListNode* curNode = head;
while(curNode != NULL){
cout << curNode->val << " -> ";
curNode = curNode->next;
}
cout << "NULL" << endl;
return;
}
void deleteLinkedList(ListNode* head){
ListNode* curNode = head;
while(curNode != NULL){
ListNode* delNode = curNode;
curNode = curNode->next;
delete delNode;
}
return;
}
ListNode* findNode(ListNode* head, int x){
ListNode* curNode = head;
while(curNode != NULL){
if(curNode->val == x)
return curNode;
curNode = curNode->next;
}
return NULL;
}
// 时间复杂度: O(1)
// 空间复杂度: O(1)
class Solution {
public:
void deleteNode(ListNode* node) {
if(node==NULL)
return;
if(node->next==NULL){
delete node;
node=NULL; //保证最后一个结点的next为NULL
return;
}
node->val=node->next->val;
ListNode* delNode =node->next;
node->next=delNode->next;
delete delNode;
return;
}
};
int main() {
int arr[] = {1, 2, 3, 4};
int n = sizeof(arr)/sizeof(int);
ListNode* head = createLinkedList(arr, n);
printLinkedList(head);
ListNode* node2 = findNode(head, 2);
Solution().deleteNode(node2);
printLinkedList(head);
deleteLinkedList(head);
return 0;
}