反轉鏈表
一、題目描述
輸入一個鏈表,反轉鏈表后,輸出新鏈表的表頭。
(看過答案和測試之后,題目隱藏條件是要求鏈表是不帶頭結點的)
二、題目思路
就是用三個指針,head、pre、next,head之前都是已經反轉好了的鏈表,next及之后的結點屬于還沒有反轉的鏈表。
三、算法實現
3.1、Java實現
/*
public class ListNode {int val;ListNode next = null;ListNode(int val) {this.val = val;}
}*/
public class Solution {public ListNode ReverseList(ListNode head) {ListNode pre=null;ListNode next=null;while(head!=null){next=head.next;head.next=pre;pre=head;head=next;}return pre;}
}
以下畫了一個示意圖
3.2、C++實現
同樣的思路:
/*
struct ListNode {int val;struct ListNode *next;ListNode(int x) :val(x), next(NULL) {}
};*/
class Solution {
public:ListNode* ReverseList(ListNode* pHead) {ListNode *pre=NULL;ListNode *next=NULL;while(pHead!=NULL){next=pHead->next;pHead->next=pre;pre=pHead;pHead=next;}return pre;}
};