在 C 中反转单向链表 [英] Reversing a singly linked list in C

查看:23
本文介绍了在 C 中反转单向链表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
如何仅使用两个指针反转单向链表?

这是用于反转链表的 C 代码.但这并没有产生所需的输出.

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;
  }

我错过了什么?

推荐答案

你没有提供足够的信息来了解更多细节,所以我猜这是一个单独喜欢的列表.如果是这样,您需要遍历您的列表一次.

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;
}

这篇关于在 C 中反转单向链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆