当前位置:网站首页>C: 反转链表
C: 反转链表
2022-06-26 20:24:00 【风静如云】
反转链表经常作为面试题,看过的解答写的都不够清晰易懂。
我是这样认为的:反转链表其实就是把链表从头部依次取出,然后再加入到另一个链表:
#include <stdio.h>
struct Node{
int data;
struct Node *next;
};
struct Node* popFromHead(struct Node **head)
{
if(*head != 0 )
{
struct Node* first = *head;
*head = first->next;
return first;
}
else
{
return 0;
}
}
void pushToHead(struct Node** head, struct Node* t)
{
t->next = *head;
*head = t;
}
void printList(struct Node *head)
{
while(head != 0)
{
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main()
{
struct Node *head = 0;
struct Node n1, n2, n3;
n1.data = 1;
n2.data = 2;
n3.data = 3;
pushToHead(&head, &n3);
pushToHead(&head, &n2);
pushToHead(&head, &n1);
printList(head);
struct Node* pNode = 0;
struct Node* reverseList = 0;
while((pNode = popFromHead(&head)) != 0)
{
pushToHead(&reverseList, pNode);
}
printList(reverseList);
return 0;
}
运行程序输出:
1 2 3
3 2 1
可见链表被反转了
边栏推荐
- Six necessary threat tracking tools for threat hunters
- On the escape of inequality value
- Is it safe to open a securities account? Is there any danger
- 威胁猎人必备的六个威胁追踪工具
- String string is converted to jsonarray and parsed
- 黑客用机器学习发动攻击的九种方法
- 数据库SQL语句撰写
- [recommended collection] these 8 common missing value filling skills must be mastered
- [MySQL series] collection of common working SQL (continuous update)
- MySQL - table creation and management
猜你喜欢
Good thing recommendation: mobile terminal development security tool
Detailed explanation of retrospective thinking
西瓜书重温(七): 贝叶斯分类器(手推+代码demo)
Feitian +cipu body brings more imagination to the metauniverse
Muke 8. Service fault tolerance Sentinel
黑客用机器学习发动攻击的九种方法
Wechat applet custom pop-up components
抖音实战~首页视频~下拉刷新
windows系统下怎么安装mysql8.0数据库?(图文教程)
Development of NFT for digital collection platform
随机推荐
慕课8、服务容错-Sentinel
0基础学c语言(1)
[most detailed] the latest and complete redis interview (70)
Tiktok practice ~ search page ~ video details
【推荐收藏】这8个常用缺失值填充技巧一定要掌握
Unit test of boot
Minimum spanning tree, shortest path, topology sorting, critical path
[most detailed] latest and complete redis interview (42 tracks)
MySQL中存储过程的详细详解
710. random numbers in the blacklist
BOM and DOM operations
JWT操作工具类分享
Database SQL statement writing
515. find the maximum value in each tree row
Is it safe to open an account for CICC Wealth Online?
c语言简单的登录
Six necessary threat tracking tools for threat hunters
好物推薦:移動端開發安全工具
Review of watermelon book (VII): Bayesian classifier (manual push + code demo)
网上开户万一免五到底安不安全?