2013-07-23 3 views
0

예 : "This is an This"로 바꿔야합니다. 한 문자는 각 노드의 정보로 저장해야합니다. 이렇게하면 전체 문장을 뒤집을 수 있습니다 (즉, "elpmaxe na si sihT").연결된 목록에서 문장의 단어를 바꾸는 방법은 무엇입니까?

#include<stdio.h> 
#include<stdlib.h> 
#include<string.h> 

struct node { 
    struct node *ptr; 
    char info; 
}; 

struct node *first,*ic; 
struct node * insertn(int n,struct node * first) 
{ 

    struct node *temp,*cur; 
    temp=(struct node *)malloc(sizeof(struct node)); 

    temp->info=n; 
    temp->ptr='\0'; 
    if(first=='\0') 
    { 

     return temp; 
    } 
    else{ 
     cur=first; 
     while(cur->ptr!='\0') 
     cur=cur->ptr; 
     cur->ptr=temp; 
     return first; 
    } 
} 
void disp(struct node *first) 
{ 
    printf("here"); 
    struct node *cur; 
    cur=first; 
    while(cur!='\0') 
    { 
     printf("%c",cur->info); 
     cur=cur->ptr; 

    } 
} 
void rev(struct node * p) 
{ 
    if(p->ptr=='\0') 
    { 

     first =p; 
     return; 
    } 

    rev(p->ptr); 

    struct node *q=p->ptr; 
    q->ptr=p; 
    p->ptr='\0'; 
} 

main() 
{ 
    char n; 
    int i=0; 

    first='\0'; 
    ic='\0'; 

    while(i<7) 
    { 

     i++; 
     printf("Enter element:"); 
     scanf("%c",&n); 
     first=insertn(n,first); 
    } 
    printf("ELEMENTS OF LIST BEFORE REV:"); 
    disp(first); 
    rev(first); 

    printf("\n\nELEMENTS OF LIST AFTER REV:"); 
    disp(first); 

} 
+0

시작 "예를 들어이입니다". –

답변

0

각 단어를 읽고 노드에 char 배열로 추가 "예를 들어이는"이제 어떻게 얻을 각 단어를 취소 할 수 있습니다. 그런 다음 연결 목록을 처음부터 끝까지 읽습니다. 문장을 뒤집을거야.

------------------------------- 
+ *prev + "This" + *next + 
------------------------------- 

------------------------ 
+ *prev + "is" + *next + 
------------------------ 

------------------------ 
+ *prev + "an" + *next + 
------------------------ 

----------------------------- 
+ *prev + "example" + *next + 
----------------------------- 

이제 * prev.

0

더 좋은 방법은 한 단어를 각 노드의 정보로 저장하는 것입니다. 이처럼 :

#define LEN 10 

struct node{ 
    struct node *ptr; 
    char info[LEN+1]; // the length of each word cannot be more than LEN 
}; 

또는

struct node{ 
    struct node *ptr; 
    char *info; 
}; 

그런 다음 당신은 당신의 목표를 달성하기 위해 회전 기능을 사용할 수 있습니다.

노드 구조체를 변경하지 않으려면 문장을 공백으로 단어로 나눠야합니다. 먼저 각 단어를 뒤집은 다음 전체 문장을 뒤집을 수 있습니다. 이처럼

: "이것은 한 예입니다"-> "elpmaxe 노나 sihT의시"- 나쁜 & 읽을 보이기 때문에>, 코드 포맷으로

관련 문제