1.題目描述
定義一個函數,輸入一個鏈表的頭節點,反轉該鏈表並輸出反轉後鏈表的頭節點。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
限制:
0 <= 節點個數 <= 5000
2.問題分析
其實倒不是很難,我們只需要兩遍遍歷即可,第一遍遍歷把鏈表中所有信息域存入數組,下標爲0存儲第一個結點的數據域,下標爲1的存儲第二個結點的數據域,依次類推。第二遍遍歷我們從頭結點開始,頭結點的數據域換成數組最後一個位置的數據,把第二個結點的數據換成數組倒數第二個位置的數據,這樣就實現了鏈表的倒置
3.代碼實現
3.1C++代碼
/**
* 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* cur=head;
int arr[5005];//存放鏈表數據域
int cnt=0;//用於記錄數組個數
while(cur)//第一次遍歷
{
arr[cnt++]=cur->val;
cur=cur->next;
}
cur=head;
while(cur)//第二次遍歷
{
cur->val=arr[--cnt];
cur=cur->next;
}
return head;
}
};
3.2Java代碼
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur=head;
int arr[]=new int[50005];
int cnt=0;
while(cur!=null)
{
arr[cnt++]=cur.val;
cur=cur.next;
}
cur=head;
while(cur!=null)
{
cur.val=arr[--cnt];
cur=cur.next;
}
return head;
}
}