两个单链表的类在实现插入节点操作时有所不同
C/C++ code
class IntSetList2 { //using List
private: int n; struct node { int val; node *next; node(int i, node *p) { val = i; next = p; } }; node *head, *sentinel;public: IntSetList2(int maxelements, int maxval) { sentinel = head =
new node(maxval, 0); n =
0; } int size() { return n; } void insert(int t) // 消除递归1
{ node *p; if (head->val == t) return; if (head->val > t) { head =
new node(t, head); n++; return; } for (p = head; p->next->val < t; p = p->next) ; if (p->next->val == t) return; p->next =
new node(t, p->next); n++; } void report(int
*v) { int j =
0; for (node *p = head; p != sentinel; p = p->next) v[j++] = p->val; }};
第二个
C/C++ code
class IntSetList3 { //using List
private: int n; struct node { int val; node *next; node(int i, node *p) { val = i; next = p; } }; node *head, *sentinel;public: IntSetList3(int maxelements, int maxval) { sentinel = head =
new node(maxval, 0); n =
0; } int size() { return n; } void insert(int t)// 消除递归2
{ node **p; for (p =
&head; (*p)->val < t; p =
&((*p)->next)) ; if ((*p)->val == t) return; *p =
new node(t, *p); n++; } void report(int
*v) { int j =
0; for (node *p = head; p != sentinel; p = p->next) v[j++] = p->val; }};
请问第二个链表的insert里面为什么要用node **p 二级指针 用一级指针行吗 为什么? |