题目:输入一个链表的头结点,反转该链表,并返回反转后链表的头结点。链表结点定义如下:
1 struct Node{ 2 object data; 3 Node *prev; 4 Node *next; 5 Node(const object &d = object(), Node *p = NULL, Node *n = NULL) 6 : data(d), prev(p), next(n) {} 7 };
1 Node* reverseNonrecurisve(Node* phead) { 2 Node* preversed_head = NULL; 3 Node* pnode = phead; 4 Node* pprev = NULL; 5 while(pnode != NULL) 6 { 7 //get the next node and save it 8 Node* pnext = pnode->next; 9 //if the next node is NULL, the current node is the new head 10 if(pnext == NULL){ 11 preversed_head = pnode; 12 13 //reverse the link between node 14 pnode->next = pprev; 15 pnode->prev = pnext; 16 17 //move forward on the list 18 pprev = pnode; 19 pnode = pnext; 20 } 21 return preversed_head; 22 }