赞
踩
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* ReverseList(ListNode* pHead) { ListNode* nHead = nullptr; //判断头结点是否为空 while(pHead != nullptr) //每次在新链表的首部插入原链表的首结点 { //不断将原链表的结点从头插入新链表 ListNode* temp = nHead; nHead = pHead; pHead = pHead->next; nHead->next = temp; } return nHead; } };
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* ReverseList(ListNode* pHead) { if(pHead == NULL || pHead->next == NULL) { return pHead; } //递归调用 ListNode* ans = ReverseList(pHead->next); //让当前结点的下一个结点的next指针指向当前节点 pHead->next->next = pHead; pHead->next = NULL; return ans; } };
复杂度分析:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。