假設單鏈表數據結構定義如下:
struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} };
單鏈表有一個頭指針指向第一個結點,最后一個結點指向NULL
一、最容易想到的方法,新建一個單鏈表newNode,每次將原先鏈表的第一個結點放到newNode后
ListNode* reverseList(ListNode* head) { ListNode *newNode = new ListNode(0);//新鏈表頭結點 ListNode *tmp;//指向原先鏈表的第一個結點 newNode->next = head; ListNode *cur = head; while(cur && cur->next) { tmp = newNode->next;//保存后續結點 newNode->next = cur->next;//將原先鏈表的第一個結點放到新鏈表中 cur->next = cur->next->next;//從原先鏈表中摘除這個結點 newNode->next->next = tmp;//恢復新鏈表中后續結點的指針 } return newNode; }
二、每次將原第一個結點后的結點放在head后面
ListNode* reverseList(ListNode* head) { ListNode *tmp = NULL; ListNode *cur = NULL; if(!head) return NULL; cur = head->next; while(cur) { tmp = cur->next; cur->next = tmp->next; tmp->next = head->next; head->next = tmp; } return head; }
三、與第二種方法類似,推薦這種方法
ListNode* reverseList(ListNode* head) { ListNode *cur = head; ListNode *tmp, *prev = NULL; while (cur) { tmp = cur->next; cur->next = prev; prev = cur; cur = tmp; } return prev; }