- UID
- 580
- 精华
- 26
- 积分
- 561
- 威望
- 28 点
- 宅币
- 341 个
- 贡献
- 0 次
- 宅之契约
- 0 份
- 最后登录
- 2015-1-29
- 在线时间
- 8 小时
用户组: 大·技术宅
- UID
- 580
- 精华
- 26
- 威望
- 28 点
- 宅币
- 341 个
- 贡献
- 0 次
- 宅之契约
- 0 份
- 在线时间
- 8 小时
- 注册时间
- 2014-12-8
|
- #include <iostream>
- using namespace std;
- struct Node
- {
- int key;
- Node* next;
- };
- Node* createList(int arr[],int nLength);
- Node* reverseList(Node* head);
- void printList(Node* head);
- void clearList(Node* head);
- void main()
- {
- int arr[] = {1,3,5,7,9};
- int nLength = sizeof(arr)/sizeof(arr[0]);
- Node* head = createList(arr,nLength);
- printList(head);
- head = reverseList(head);
- printList(head);
- clearList(head);
- }
- Node* createList(int arr[],int nLength)
- {
- Node* head = new Node;
- head->key = arr[0];
- head->next = NULL;
- Node *p = head;
- for(int i=1;i<nLength;i++)
- {
- Node* ptr = new Node;
- ptr->key = arr[i];
- ptr->next = NULL;
- p->next = ptr;
- p = p->next;
- }
- return head;
- }
- Node* reverseList(Node* head)
- {
- Node* preNode = NULL;
- Node* pNode = head;
- while( pNode != NULL )
- {
- Node* pNext = pNode->next;
- pNode->next = preNode;
- preNode = pNode;
- pNode = pNext;
- }
- return preNode;
- }
- void printList(Node* head)
- {
- Node* p = head;
- while( p!= NULL )
- {
- cout<<p->key<<endl;
- p=p->next;
- }
- }
- void clearList(Node* head)
- {
- Node* p = head;
- Node* ptr;
- while( p!= NULL )
- {
- ptr = p->next;
- delete p;
- p = ptr;
- }
- }
复制代码 |
|