2015-01-08 3 views
-1

링크 된 목록의 첫 번째 요소를 가리키는 "* FIRST"포인터를 어떻게 삭제합니까? 첫 번째 요소를 삭제하려면?체인 된 목록의 노드 삭제

-my 문제는 첫 번째 노드를 삭제할 때 포인터가 두 번째 노드에서 가리키는 점입니다. 그러나 내가 가리키는 요소의 주소를 표시하면 FIRST = NULL이 발견됩니다.

미리 감사드립니다.

#include <stdio.h> 
#include <stdlib.h> 
typedef struct 
{int note; 
struct personne *next; 
}personne; 
personne *first=NULL; 

void saisi (personne *first,int mark) 
{ personne *nouveau=malloc(sizeof(personne)); 
    nouveau->note=mark; 
    nouveau->next=NULL; 
    if(first==NULL) 
    first=nouveau; // here is the problem 
else 
{ personne *tmp; 
    tmp=first; 
while (tmp->next!=NULL) tmp=tmp->next; 
    tmp->next=nouveau; 
} 
} 
void affichage (personne *first) 
{int i=1; 
    personne *tmp; 
tmp=first; 
    do 
    {printf("la note %d : %d \n",i,tmp->note); 
    i++;tmp=tmp->next; 
    }while (tmp!=NULL); 
} 
void suppresion (personne *first,int n) 
{personne *tmp1=NULL,*tmp2=NULL; 
    tmp1=first; 
while (tmp1 != NULL) 
{ if ((tmp1->note) >n){ 
    tmp2->next=tmp1->next; 
} 
    tmp2=tmp1; 
    tmp1=tmp1->next; 
} 

} 
int main() 
{ 
int N=1,mark=0,n=0; 
while (N!=4) 
{ printf ("donner la note %d:",N); 
    scanf ("%d",&mark); 
    saisi (first,mark); 
    N++; 
} 
    affichage (first); 
    printf("donner n :"); 
    scanf("%d",&n); 
    suppresion (first,n); 
    affichage(first); 
    return 0; 
} 
+0

void saisi (personne **ppfirst, int mark) { personne **ppnode = ppfirst; personne *nouveau=malloc(sizeof(personne)); nouveau->note=mark; nouveau->next=NULL; while(*ppnode != NULL) ppnode = &((*ppnode)->next); *ppnode = nouveau; } void suppresion (personne **ppfirst, int n) { personne **ppnode = ppfirst; personne *pnode; while (*ppnode != NULL) { if((*ppnode)->note > n){ pnode = *ppnode; *ppnode = (*ppnode)->next; free(pnode); } else { ppnode = &((*ppnode)->next); } } } /* ... */ saisi(&first, mark); /* ... */ suppresion(&first, n); 
(하나의 별표). – dasblinkenlight

답변

0

dasblinkenlight 의해 주석으로 포인터에 대한 포인터를 사용

연결리스트의 요소를 삭제하는 트릭 오히려 포인터 자체보다, 헤더 포인터 포인터 (별표 두 개)을 전달하는
0

1. "first"는 전역 변수이므로 각 함수 호출시 인수로 전달할 필요가 없습니다.

2.- "suppresion"방법에서 "temp2-> next"를 호출하려고하면 "temp2"가 NULL을 가리킬 수 있습니다.

3. 목록의 요소를 삭제할 때 메모리를 확보해야합니다.

4.- 나는 당신이 무엇을 요구하고 있는지 잘 이해하지 못한다. 그러나 링크드리스트의 많은 요소들을 지우고 싶다면 여기에 방법이 모든 노드를 삭제한다고 가정 할 때 억압 법을 만들 수있다. A (표> N)와 :

void suppresion (int n) 
{ 
    personne *tmp1=NULL,*tmp2=NULL; 

    tmp1=first; 

    //First check all elements except the first one 
    while (tmp1 != NULL) 
    { 
     if ((tmp1->next != NULL)&&(tmp1->next->note >n)) 
     { 
      tmp2=tmp1->next; 
      tmp1->next = tmp2->next; 
      free(tmp2); 
     } 
     else 
     { 
      tmp1=tmp1->next; 
     } 
    } 
    //Now go for the first element 
    if(first != NULL && first->note > n) 
    { 
     tmp1 = first; 
     first = tmp1->next; 
     free(tmp1); 
    } 
} 

이 방법은, 어레이의 모든 요소를 ​​검색하고, 모든 마크가 소자> N 한 메소드 호출하여 삭제하는 것이; 일반적으로 구체적인 요소를 삭제하고 코드의 다른 섹션에있는 루프에서 호출하는 메서드를 만듭니다.

관련 문제