首页 > 代码库 > 单链表逆置
单链表逆置
重写单链表逆置,熟能生巧~
#include <iostream> #include <cstdlib> using namespace std; typedef struct List{ int num; struct List *next; }ListNode,*pListNode; void display(ListNode *pHead) { while(pHead) { cout<<pHead->num<<"--"; pHead = pHead->next; } cout<<endl; } ListNode* ReverseListNode(ListNode *pHead) { ListNode* curNode = pHead; ListNode* preNode = pHead->next; ListNode* nextNode = preNode->next; curNode->next = NULL; while(nextNode) { preNode->next = curNode; curNode = preNode; preNode = nextNode; nextNode = nextNode->next; } preNode->next = curNode; return preNode; } int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; ListNode* pHead = (struct List*)malloc(sizeof(struct List)); pHead->num = 0; pHead->next = NULL; for(int i = 0; i < 10; i++) { ListNode *pNode = (struct List*)malloc(sizeof(struct List)); pNode->num = arr[i]; pNode->next = NULL; pNode->next = pHead->next; pHead->next = pNode; } ListNode* pTemp = pHead; while(pTemp) { cout<<pTemp->num<<"--"; pTemp = pTemp->next; } cout<<endl; ListNode* pTemp2 = ReverseListNode(pHead); while(pTemp2) { cout<<pTemp2->num<<"--"; pTemp2 = pTemp2->next; } cout<<endl; return 0; }
单链表逆置
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。