面试金典--删除链表某个节点,只能访问该节点

题目2.3:实现一个算法,删除单向链表中间的某个节点,只能访问该节点。

将后续节点的值复制到当前节点即可,但是最后一个节点就不能删除了。另外我的实现中没考虑只有一个节点或者为空的情况

 1 #include <iostream>
 2 #include <string>
 3 #include <fstream>
 4 #include <map>
 5 #include <algorithm>
 6 #include <vector>
 7 #include <ctime>
 8 #include <bitset>
 9 
10 using namespace std;
11 
12 template<typename T>
13 class Node
14 {
15 public:
16     Node<T> *next;
17     T data;
18 
19     Node(T d):data(d),next(NULL){}
20     void appendToTail(T d)
21     {
22         Node<T> *end = new Node<T>(d);
23         Node<T> *n = this;
24         while(n->next != NULL)
25         {
26             n = n->next;
27         }
28         n->next = end;
29     }
30 };
31 
32 int main()
33 {
34     Node<int> *head = new Node<int>(1);
35     int i;
36     for(i = 2 ; i < 6 ; ++i)
37     {
38         head->appendToTail(i);
39     }
40     //2.3
41     int obj = 2;
42     //首先判断是否小于等于一个节点数
43     //假设大于1个节点数
44     Node<int> *headorg = head;
45     if(head->data == obj)
46         headorg = head->next;
47     else
48     {
49         while(head->data != obj)
50         {
51             head = head->next;
52         }
53         head->data = head->next->data;
54         head->next = head->next->next;
55     }
56     while(headorg != NULL)
57     {
58         cout<<headorg->data<<endl;
59         headorg = headorg->next;
60     }
61     return 0;
62 }
原文地址:https://www.cnblogs.com/cane/p/3789315.html