Home > Back-end >  Questions about the singly linked list delete specified location nodes
Questions about the singly linked list delete specified location nodes

Time:05-11

Int ListDelete (LinkList * L, int I ElemType * e)
{
Int j;
LinkList p, q;
P=* L;
j=1;
While (p - & gt; Next & amp; & J & lt; I)
{
P=p - & gt; Next;
+ + j;
}
if (! (p - & gt; Next) | | j & gt; I)
return 0;
Q=p - & gt; Next;
P - & gt; Next=q - & gt; Next;
* e=q - & gt; The data;
free(q);
return 1;
}

Assuming that the length of the list of 5, to remove node on the position I=3
In the above code, p=* L can be understood as p refers to the first node list L, so in a subsequent part while:
The first cycle (j=1), p - & gt; Next is not empty, and j & lt; I, the executive p=p - & gt; Next, at this point p point should be first active node list L, j since 1,
The second cycle (j=2), p - & gt; Next is not empty, and j & lt; I, the executive p=p - & gt; Next, at this point p point should be the second effective node list L, j since 1,
The third cycle (j=3), p - & gt; Next is not null, but j=I, does not meet the requirements for the while judgement, and directly out of the while loop perform subsequent operations, at this time j=3, p points to is the first in the list L I - a node of the location, in this case for the second node list L,

After subsequent use q temporarily hold p node p - & gt; The pointer to the next, then p node domain subsequent changes to q node address, thus completed I=3 position from the list L node to remove operation,

The above content, look no problem, but always feel a bit strange, can't say where to blame, a big help watching the

CodePudding user response:

The problem:
 int ListDelete (int I LinkList * L, ElemType * e) 
{
Int j;
LinkList p, q;
P=* L;
j=1;
While (p - & gt; Next & amp; & J & lt; I)
{
P=p - & gt; Next;
+ + j;
}
if (! (p - & gt; Next) | | j & gt; I) the return 0;
Q=p - & gt; Next;//q point I=3 nodes head
P - & gt; Next=q - & gt; Next;//p - & gt; The end of the next point to I=3 nodes, namely I=4 nodes of the head,
//equal to p - & gt; Next=p - & gt; Next - & gt; Next, I=2 nodes of the tail pointer to I=4 head
* e=q - & gt; The data;
free(q);//release q
return 1;
}

CodePudding user response:

Delete this code in addition to the first node of the node is no problem, but if you remove the head node, this will have a problem, need to additional handling ~

CodePudding user response:

There are, I hope it can help you: https://blog.csdn.net/it_xiangqiang/category_10768339.html,
  • Related