日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C語言中如何實現單鏈表刪除指定結點_C 語言

作者:nefu_lmy ? 更新時間: 2022-09-05 編程語言

單鏈表刪除指定結點

在單鏈表中刪除指定的結點。這里單鏈表是用尾插法建立的,因為尾插法輸出的順序與輸入的順序是相同的。

#include <bits/stdc++.h>
using namespace std;
 
typedef struct node
{
    int data;
    struct node *next;
}no;
 
int main()
{
    no *head,*tail,*p,*r,*q;
    head=new no;
    head->next=NULL;
    tail=head;
    int n,k;
    printf("一共要輸入的數: ");
    scanf("%d\n",&n);
    //尾插法建立單鏈表
    for(int i=0;i<n;i++)
    {
        cin>>k;
        p=new no;
        p->data=k;
        p->next=NULL;
        tail->next=p;
        tail=p;
    }
    //接下來是刪除操作
    int m;
    printf("輸入要刪除的數: ");
    scanf("%d",&m);
    p=head;//讓p指針從頭結點開始遍歷,要注意的是,頭結點是沒有數值的哦!
    while(p->data!=m&&p->next!=NULL)//循環查找要刪除的結點
    {
        r=p;
        p=p->next;//把p的下一個結點給p,所以p就不是原來的p了,原來的p變成了r
      if(p->data==m)//因為頭結點沒有數值,所以一開始就讓p=p->next是對的
      {
          r->next=p->next;//將要刪除結點的前一個結點指向它的下一個結點(原本是要指它的,現在指向它的下一個結點了)(r是要刪除結點的前一個結點)  
          delete(p);
      }//注意,這里的p->next已經和第38行的p->next不一樣了,它是38行的下一個結點了
    }
    q=head->next;
    for(int i=0;i<n-1;i++)
    {
        printf("%d ",q->data);
        q=q->next;
    }
    return 0;
}

測試一:一共要輸入的數:5

? ? ? ? ? ? ? 1 2 3 4 5

? ? ? ? ? ? ? 要刪除的數:5

? ? ? ? ? ? ? 輸出:1 2 3 4

測試二:一共要輸入的數:5

? ? ? ? ? ? ? 1 2 3 4 5

? ? ? ? ? ? ? 要刪除的數:1

? ? ? ? ? ? ? 輸出: 2 3 4 5

測試三:一共要輸入的數:5

? ? ? ? ? ? ? 1 2 3 4 5

? ? ? ? ? ? ? 要刪除的數:2

? ? ? ? ? ? ? 輸出:1 3 4 5

鏈表的刪除結點(各種方法)

先建立鏈表(代碼在最后)

鏈表中刪除第i個結點

int main()
{
? ? int i;
? ? Node *p,*head,*k;
? ? head=setlink();
? ? scanf("%d",&i);
? ? int v=1;
? ? for(p=head->next;p!=NULL;k=p,p=p->next) ?
? ? {
?? ??? ?if(v==i)break;
?? ??? ?else{
?? ??? ??? ?v++;
?? ??? ?}
?? ??? ? ??
? ? }
?? ??? ?k->next=p->next;
?? ?
?? ? delete(p);
?? ? ? ?for(p=head->next;p!=NULL;p=p->next)
?? ??? ? ? printf("%d ",p->id);
?? ? return 0 ;
}

刪除與鏈表中與a相同的結點

int main()
{
?? ?int a;
?? ?Node *p,*q,*heada,*k;
?? ?heada=setlink();
?? ?scanf("%d",&a);
?? ?for(p=heada->next;p!=NULL;k=p,p=p->next) ?
?? ?{
?? ??? ?if(p->id==a)
?? ??? ?{
?? ??? ??? ?q=p;
?? ??? ??? ?k->next=p->next;
?? ??? ??? ?p=k->next;
?? ??? ??? ?delete(q);
?? ??? ?}
?
?? ?}
?? ?for(p=heada->next;p!=NULL;p=p->next)
?? ??? ?printf("%d ",p->id);
?? ?return 0 ;
}

刪除鏈表中重復元素

int main()
{
?? ?Node *p,*q,*heada,*k,*ptr;
?? ?heada=setlink();
?? ?for(p=heada->next;p!=NULL;p=p->next) ?
?? ?{
?? ??? ?k=p;
?? ??? ?for(q=p->next;q!=NULL;k=q,q=q->next)
?? ??? ?{
?? ??? ?if(p->id==q->id)
?? ??? ?{
?? ??? ??? ?ptr=q;
?? ??? ??? ?k->next=q->next;
?? ??? ??? ?q=k;
?? ??? ??? ?free(ptr);
?? ??? ?}
?? ??? ?}
?? ?}
?? ?for(p=heada->next;p!=NULL;p=p->next)
?? ??? ?printf("%d ",p->id);
?? ?return 0 ;
}

原文鏈接:https://blog.csdn.net/nefu_lmy/article/details/119081408

欄目分類
最近更新