Reversing a singly linked list in C [duplicate]

别说谁变了你拦得住时间么 提交于 2019-12-02 10:41:50

问题


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:

  1. Write unit tests for your code. Start with an empty list, a list with one element, then two, then three.

  2. Run the code in a debugger.

  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!