The deletion of the first element in the case of a single linked list without knowing the head node

Source: Internet
Author: User

First, take a look at the deletion of element I in the single-linked list:

Status listdelete_l (linklist &l,int i,elemtype &e) {

in the single-linked table L of the lead node, delete the element I , and return its value by E

p=l;j=0;

while (p->next&&j<i-1) {// finds The first node and points p to its predecessor

p=p->next;

++j;

}

if (! ( P->next) | |  J<I-1) return ERROR; The deletion of the location is unreasonable

q=p->next;p->next=q->next; Delete and Release nodes

E=q->data;free (q);

return OK;

}

For example, delete the 3rd element C in the single-linked list L, i.e. delete the 4th node:

1) At the beginning, the P pointer points to the head node,j=0;

2) Executes the loop statement, when j=2 ,p points to the third node, the loop ends;

3) q=p->next;p->next=q->next; Delete and release nodes;

The deletion of C nodes is implemented.

Second, the single-linked list of the first node in the case of the deletion of the first element:

For example, the deletion of the B-node, the first only to know the pointer to the B-node q, because it is a single-linked list, cannot get to the precursor pointer, so the above method can not be deleted.

You can use the following statement to implement the deletion of the Q node:

q->data=q->next->data;

q->next=q->next->next;

At this point, theL single-linked list becomes:

Although the C node is deleted, it copies the data in C to B, which is equivalent to deleting the b node.

Note, however, that this deletion method cannot delete a node at the end of the table because there is no other node in the back that can be replaced.

The deletion of the first element in the case of a single linked list without knowing the head node

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.