剑指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;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43624053/article/details/84912956