【100题】反转链表

来源:互联网 发布:万方地方志数据库网址 编辑:程序博客网 时间:2024/04/28 00:47
//#include <iostream>using namespace std;struct ListNode{int data;struct ListNode *next;};//创建链表void createList(ListNode *&Head){ int num = 0; int flag = 0; ListNode *p = NULL; cin >> num;  Head = (ListNode *)malloc(sizeof(ListNode)); while(num != 0) {  if(flag == 0)  {     Head->data = num;   Head->next = NULL;   flag = 1;   p = Head;  }  else  {   ListNode *cur = (ListNode *)malloc(sizeof(ListNode));   cur->data = num;   cur->next = NULL;     p->next = cur;   p = cur;  }   cin >> num; }}//打印链表void printList(ListNode *Head){ if(Head == NULL) {  cout << "Head empty"<<endl;  return ; } ListNode *p = Head; while(p != NULL) {  cout << p->data <<" ";  p = p->next; }}//非递归反转链表ListNode *ReverseIteratively(ListNode *pHead){ListNode *pReverseHead = NULL;ListNode *pNode = pHead;ListNode *pPrev = NULL;while(pNode != NULL){ListNode *pNext = pNode->next;if(pNext == NULL){pReverseHead = pNode;}pNode->next = pPrev;pPrev = pNode;pNode = pNext;}return pReverseHead;}void main(){ ListNode *List = NULL; cout << "创建链表:"; createList(List); cout << "链表元素:"; printList(List); List = ReverseIteratively(List); cout <<endl<< "倒序后:"; printList(List);}