劍指offer(15)反轉鏈表

題目描述
輸入一個鏈表,反轉鏈表後,輸出新鏈表的表頭。
解題思路

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if(pHead==NULL) return pHead;
        ListNode* tmp=nullptr;
        ListNode* pre=nullptr;
        ListNode* res=nullptr;
        ListNode* current=pHead;
        while(current!=NULL)
        {
            tmp=current->next;
            current->next=pre;
            if(tmp==NULL) res=current;
            pre=current;
            current=tmp;
        }
        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章