首页 > 技术文章 > 每日一道面试题-01

heyjia 2019-08-08 10:31 原文

题目:如何实现一个高效的单向链表逆序输出

思路:对链表的逆序输出,需要3个指针分别指向pre cur 和cur的next,对第一次遍历,把当前节点的next指向上一个节点,而需要用指针保存下一个节点(默认head的data无数据)

代码

typedef struct node
{
int data; struct node *next; }LinkNode; void reverse(LinkNode *head) { if (head == null || head -> next == null)
    {
   return; }
LinkNode * pre,*cur,*next;
    pre = null;
cur = head->next;
while(cur != null)
{
if (cur ->next == null)
{
        cur -> next = pre;
break;
      }
next = cur -> next;
cur -> next = pre;
pre = cur;
cur = next;
}
head ->next = cur;
LinkNode *temp = head->next;
while (temp != null)
{
printf("%d ",temp->data);
temp = temp ->next;
}
}

 

推荐阅读