题目描述:
输入一个链表,反转链表后,输出链表的所有元素。
算法思想:
其实这个题目并不是很难,我们需要注意的就是在一些边界问题的处理上。使它的鲁棒性更好。我们只需记录三个指针,来改变三个指针的值去交换即可。
算法实现:
1 #include<iostream> 2 #include<stdlib.h> 3 using namespace std; 4 5 typedef struct ListNode{ 6 int data; 7 struct ListNode *next; 8 }ListNode; 9 10 ListNode* ReverseList(ListNode *pHead){ //翻转链表 11 if(pHead == NULL){ 12 return NULL; 13 } 14 15 ListNode *PreNode = NULL; 16 ListNode *node = pHead; 17 ListNode *NewNode = NULL; 18 19 while(node != NULL){ 20 ListNode *pNext = node->next; 21 if(pNext == NULL){ 22 NewNode = node; 23 } 24 25 node->next = PreNode; 26 PreNode = node; 27 node = pNext; 28 } 29 pHead->next = NULL; 30 return NewNode; 31 } 32 33 ListNode *CreateList(int x){ //创建链表 34 long num; 35 ListNode *pHead = NULL; 36 ListNode *p = NULL; 37 38 while(x-- > 0){ 39 cin>>num; 40 ListNode* pNew = new ListNode(); 41 if(pNew == NULL){ 42 exit(EXIT_FAILURE); 43 } 44 pNew->data = num; 45 pNew->next = NULL; 46 47 if(pHead == NULL) 48 { 49 pHead = pNew; 50 p = pHead; 51 } 52 else 53 { 54 p->next = pNew; 55 p = p->next; 56 } 57 } 58 return pHead; 59 } 60 61 void print(ListNode* pHead){ //输出翻转后的链表 62 if(pHead == NULL){ 63 cout<<"NULL"<<endl; 64 } 65 else 66 { 67 ListNode *p = pHead; 68 while(p != NULL){ 69 cout<<p->data<<" "; 70 p = p->next; 71 } 72 cout<<endl; 73 } 74 } 75 76 int main(){ 77 int n; 78 ListNode *head = NULL; 79 ListNode *trail = NULL; 80 81 while(cin>>n){ 82 head = CreateList(n); 83 trail = ReverseList(head); 84 if(trail == NULL){ 85 cout<<"NULL"<<endl; 86 } 87 else{ 88 print(trail); 89 } 90 } 91 92 return 0; 93 }