char *를 LinkedList에 추가하여 linkedList가 항상 사전 순으로 정렬되도록하는 방법을 만들고 있습니다.정렬 된 순서로 포인터에 문제가 발생했습니다.
// Adds a new item to the beginning of a list, returning the new
// item (ie the head of the new list *)
ListItem* add_item(ListItem *p_head, char *s) {
// Allocate some memory for the size of our structure.
ListItem *p_new_item = malloc(sizeof(ListItem));
p_new_item->p_next = p_head; // We are the new tail.
p_new_item->s = s; // Set data pointer.
return p_new_item;
}
지금 여기에 내가 ', 내 코드입니다 : 나는 또한 목록의 시작 부분에 항목을 추가하는 방법을 주어졌다
// Define our list item as 'struct ListItem', and also
// typedef it under the same name.
typedef struct ListItem {
char *s;
struct ListItem *p_next;
} ListItem;
: 나는 LinkedItem 구조체를 정의하는 코드를 주어졌다 더 후 설명 할 것이다 : A와 B의 올바른 정렬 된 순서는 A, 그 다음 B, 거짓 otherwise- 평등 경우 지금
ListItem* addSortedItem(ListItem *p_head, char *s){
if(p_head==NULL)//if the list is empty, we add to the beginning
return add_item(p_head,s);
ListItem* p_new_item = malloc(sizeof(ListItem));
ListItem *p_current_item = p_head; //makes a pointer to the head of the list
while (p_current_item) { // Loop while the current pointer is not NULL
printf("entering while loop with current=%s\n",p_current_item->s);
// now we want to look at the value contained and compare it to the value input
if(aThenB(s,p_current_item->s)!=TRUE){
// if A goes after B, we want to go on to look at the next element
p_current_item=p_current_item->p_next;
} else if (aThenB(s,p_current_item->s)==TRUE) {printf("entered elseif\n");
p_head=add_item(p_current_item,s);
return p_head;
} else {printf("WHY DID WE EVER REACH THE ELSE!?"); return p_head;}
}
}
, aThenB (StringA, StringB)가 true를 돌려주는 것은 옵션, 나는 단순히 천국도 이거 작동하지 않아. l :
내 테스트 데이터 (0에서 10까지의 숫자 인 "sheep i"
)는 하나의 요소 만 반환하거나 임의로 요소를 건너 뛸 때 발생합니다. 주문 입력. 더 많은 코드를 포함 할 수 있지만 약간 지저분합니다.
필자의 문제점은 포인터를 완전히 이해하지 못하고 어떻게 동작하는지에 기인한다고 생각합니다. p_head가 항상 머리를 가리키고, p_current가 목록을 통해 이동하고 있음을 보장하고자합니다. 하지만 p_current가 마지막 요소에 도달하면 seg faults가 발생하므로 어디서 잘못 될지 잘 모르겠습니다.() main 메소드에 다음 블록에서 호출 addSortedItem : 처음에는
// The empty list is represented by a pointer to NULL.
ListItem *p_head = NULL;
ListItem *p_head2=NULL;
// Now add some items onto the beginning of the list.
int i;
for (i=0; i<NO_ITEMS; i++) {
// Allocate some memory for our string, and use snprintf to
// create a formatted string (see GNU API docs) much like printf
// but instead writing to memory rather than the screen.
char* s = malloc(MAX_DATA_CHARS);
snprintf(s, (size_t) MAX_DATA_CHARS, "sheep %d", i);
p_head = addSortedItem(p_head, s);
}
aThenB()는 무엇을합니까? –
두 번 째 매개 변수 (stringA와 stringB)를 한 번에 한 문자 씩 비교하고, stringB
benbenbenbenben
'addSortedItem'을 호출하는 코드를 포함하십시오. 함수가 문자열의 소유권을 연결된 목록으로 전송하는 방식 때문에 여러 가지 상황을 망칠 기회가 많이 있습니다. – dasblinkenlight