我已經創建了一個鏈接列表,但無法想象如何反轉相同。我知道算法,但我認爲我在創建列表時犯了一個錯誤。反函數中的變化可能會起作用。 以下是代碼:如何反轉我在C中創建的鏈接列表
typedef struct Node{
int data;
struct Node* next;
} node;
node* head;
int count;
void insertAtBegin(int value){
if(head==NULL){
head = (node*)malloc(sizeof(node));
head->data = 0;
head->next = NULL;
}
node* newNode = (node*)malloc(sizeof(node));
newNode->data = value;
newNode->next = head->next;
head->next = newNode;
count++;
}
void display(){
node* temp = (node*)malloc(sizeof(node));
temp = head;
while(temp->next!=NULL){
printf("%d\t",temp->next->data);
temp = temp->next;
}
printf("\n");
}
void reverse(){
node *p, *q, *r;
p = q = r = head;
p = p->next->next;
q = q->next;
r->next = NULL;
q->next = r;
while (p != NULL){
r = q;
q = p;
p = p->next;
q->next = r;
}
head = q;
}
void main(){
insertAtBegin(5);
insertAtBegin(6);
display();
reverse();
display();
printf("\nSize of linked list is %d",count);
}
'node * temp =(node *)malloc(sizeof(node)); temp = head;'是內存泄漏。爲什麼要在顯示節點時分配節點? – mch
開始編碼自己,然後提出問題,如果你有困難。 –
@mch好吧,我沒有想法..謝謝,但這可能無法解決我的逆轉問題... –