一、題目
網址:反轉鏈表。
難度:簡單。
反轉一個單鏈表。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
進階:
你可以迭代或遞歸地反轉鏈表。你能否用兩種方法解決這道題?
二、程序
思路:使用迭代的思想,每次反轉一個,講next的地址指向前一個元素,同時不斷更新頭節點和新建的頭節點。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* new_head=NULL;
while(head)
{
ListNode* next=head->next;
head->next=new_head;
new_head=head;
head=next;
}
return new_head;
}
};
結果: