反转链表
Posted 三颗心
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了反转链表相关的知识,希望对你有一定的参考价值。
题目:定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
思路1:定义三个指针,分别指向当前遍历到的结点、它的前一个结点及后一个结点。
思路2:递归
1 #include<stdio.h> 2 #include<tchar.h> 3 #include<iostream> 4 struct ListNode 5 { 6 int m_nValue; 7 ListNode* m_pNext; 8 }; 9 10 ListNode* CreateListNode(int value) 11 { 12 ListNode* pNode = new ListNode(); 13 pNode->m_nValue = value; 14 pNode->m_pNext = NULL; 15 16 return pNode; 17 } 18 19 void PrintList(ListNode* pHead) 20 { 21 printf("PrintList starts.\\n"); 22 ListNode* pNode = pHead; 23 while(pNode != NULL) 24 { 25 printf("%d\\t",pNode->m_nValue); 26 pNode = pNode->m_pNext; 27 } 28 printf("\\nPrintList ends.\\n"); 29 } 30 31 void DestoryList(ListNode* pHead) 32 { 33 ListNode* pNode = pHead; 34 while(pNode != NULL) 35 { 36 pHead = pHead->m_pNext; 37 delete pNode; 38 pNode = pHead; 39 } 40 } 41 42 void ConnectListNodes(ListNode* pCurrent, ListNode* pNext) 43 { 44 if(pCurrent == NULL) 45 { 46 printf("Error to connect two nodes.\\n"); 47 exit(1); 48 } 49 50 pCurrent->m_pNext = pNext; 51 } 52 53 54 //循环, 定义三个指针 55 ListNode* ReverseList1(ListNode* pHead) 56 { 57 ListNode* pReversedHead = NULL; 58 ListNode* pNode = pHead; 59 ListNode* pPrev = NULL; 60 while(pNode != NULL) 61 { 62 ListNode* pNext = pNode->m_pNext; 63 64 if(pNext == NULL) 65 pReversedHead = pNode; 66 67 pNode->m_pNext = pPrev; 68 69 pPrev = pNode; 70 pNode = pNext; 71 } 72 73 return pReversedHead; 74 } 75 76 77 //递归 将当前结点的下一个结点保存好, 并将当前结点从链表中取出,再递归处理以后的链表 78 ListNode* ReverseList2(ListNode* pNode) 79 { 80 if(pNode->m_pNext == NULL) 81 return pNode; 82 83 ListNode* pNext = pNode->m_pNext; 84 pNode->m_pNext = NULL; 85 ListNode* pReversedHead = ReverseList2(pNext); 86 pNext->m_pNext = pNode; 87 return pReversedHead; 88 } 89 90 int main() 91 { 92 ListNode* pNode1 = CreateListNode(1); 93 ListNode* pNode2 = CreateListNode(2); 94 ListNode* pNode3 = CreateListNode(3); 95 ListNode* pNode4 = CreateListNode(4); 96 ListNode* pNode5 = CreateListNode(5); 97 98 ConnectListNodes(pNode1, pNode2); 99 ConnectListNodes(pNode2, pNode3); 100 ConnectListNodes(pNode3, pNode4); 101 ConnectListNodes(pNode4, pNode5); 102 103 printf("Sloution1:\\n"); 104 printf("The original list is: \\n"); 105 PrintList(pNode1); 106 107 ListNode* pReversedHead = ReverseList1(pNode1); 108 109 printf("The reversed list is: \\n"); 110 PrintList(pReversedHead); 111 112 printf("\\n"); 113 114 printf("Sloution2:\\n"); 115 printf("The original list is: \\n"); 116 PrintList(pReversedHead); 117 118 pReversedHead = ReverseList2(pReversedHead); 119 120 printf("The reversed list is: \\n"); 121 PrintList(pReversedHead); 122 123 DestoryList(pReversedHead); 124 125 return 0; 126 }
以上是关于反转链表的主要内容,如果未能解决你的问题,请参考以下文章