问题
Possible Duplicate:
How to reverse a singly linked list using only two pointers?
This is C code to reverse a linked list. But this isn't producing the desired output.
struct node *temp,*prev;
while(head->next!=NULL)
{
temp=prev=head;
while(temp->next->next!=NULL)
{
temp=temp->next;
prev=prev->next;
}
temp=temp->next;
temp->next=prev;
prev->next=NULL;
}
What am I missing?
回答1:
You don't provide enough informations to have more details, so I guessed it is a singly liked list. If so, you need to run through your list once.
void reverse(struct node **p) {
struct node *buff = NULL;
struct node *head = *p;
while (head != NULL) {
struct node *temp = head->next;
head->next = buff;
buff = head;
head = temp;
}
*p = buff;
}
回答2:
You will ask yourself this question often in your career, so it's important that you come up with a solution for this. Here are some pointers:
Write unit tests for your code. Start with an empty list, a list with one element, then two, then three.
Run the code in a debugger.
Add debug
printf()
statements which show you what the code does as it executes.
来源:https://stackoverflow.com/questions/13254218/reversing-a-singly-linked-list-in-c