复习下单链表的逆置,留作后看:
先上张图,便于理解代码:
代码贴上:
1 /************************************************************************/ 2 /* create by leisc 2014.07.11 */ 3 /************************************************************************/ 4 5 #include <iostream> 6 using namespace std; 7 8 typedef struct _listnode 9 { 10 int data; 11 _listnode *pNext; 12 }LISTNODE; 13 14 //打印链表 15 int printlist(const LISTNODE *head) 16 { 17 int ret = 0; 18 if (head == NULL) 19 { 20 ret = -1; 21 return ret; 22 } 23 cout << endl; 24 for (LISTNODE *tmp = (LISTNODE*)head->pNext; tmp != NULL; tmp = tmp->pNext) 25 { 26 printf("%d ", tmp->data); 27 } 28 cout << endl; 29 return ret; 30 } 31 32 int CreateAndIniList(LISTNODE ** list) 33 { 34 int n = 1;//记录链表元素数量 35 int cdata = 0;//链表元素数据存储 36 int ret = 0; 37 38 LISTNODE *pHead = NULL; 39 LISTNODE *pTmp = NULL; 40 LISTNODE *pCur = NULL; 41 //c写法创建新节点 42 //pPri = pCur = (LISTNODE *)malloc(sizeof(LISTNODE)); 43 pHead = pCur = new LISTNODE; 44 if (pCur == NULL || pHead == NULL) 45 { 46 ret = -1; 47 return ret; 48 } 49 50 //头节点初始化 51 pHead->data = 0; 52 pHead->pNext = NULL; 53 pCur = pHead; 54 55 cout << "Please enter the data you want to insert into the list(enter -1 to end!):" << endl; 56 cout << "The " << n << "'th node data:"; 57 cin >> cdata; 58 //循环添加链表元素,采用尾插法 59 while (cdata != -1) 60 { 61 pTmp = new LISTNODE; 62 63 pTmp->data = cdata; 64 65 pTmp->pNext = NULL; 66 67 pCur->pNext = pTmp; 68 pCur = pTmp; 69 n++; 70 cout << "The" << n << "'th node data:"; 71 cin >> cdata; 72 } 73 74 *list = pHead; 75 return ret; 76 } 77 78 int ReverseList(LISTNODE **list) 79 { 80 if (list == nullptr)//判断是否是空链表 81 { 82 return -1; 83 } 84 85 //申请新节点,将入参接过来 86 LISTNODE* reList = new LISTNODE; 87 reList = *list; 88 89 //判断是否是空链表或者只有一个元素 90 if (reList->pNext == nullptr ||reList->pNext->pNext == nullptr) 91 { 92 return -1; 93 } 94 95 //采用双节点跳马式循环修改指针指向 96 LISTNODE* pPre = nullptr; //指向前面一个节点 97 LISTNODE* pCur = nullptr; //指向后面一个节点 98 99 pPre = reList->pNext; //将pPre指向第一个节点 100 pCur = pPre->pNext; //将pCur指向第二个节点 101 //reList->pNext = nullptr; //这里可以将头节点指空,当然就那么放着也行 102 pPre->pNext = nullptr; //首先需要把第一个节点的的指向赋空,要不然就死循环了 103 LISTNODE* pTemp = nullptr; //申请一个缓存指针,用于存储向后的节点地址 104 105 //循环进行指针逆置 106 while (pCur) 107 { 108 pTemp = pCur->pNext;//将pCur的下一个地址缓存起来 109 pCur->pNext = pPre; //将pCur的下一个指向他的前一个,即pPre 110 //两个指针同时向后跳一 111 pPre = pCur; 112 pCur = pTemp; 113 } 114 115 //最后将头节点指向逆置后的第一个节点,即pPre 116 reList->pNext = pPre; 117 118 return 0; 119 } 120 121 int main() 122 { 123 LISTNODE *pHead = NULL; 124 125 CreateAndIniList(&pHead); 126 cout << "原始链表:" << endl; 127 printlist(pHead); 128 129 ReverseList(&pHead); 130 131 cout << "逆序后的链表" << endl; 132 printlist(pHead); 133 134 return 0; 135 }
运行结果: