题目来源:牛客网
解题思路
- 指针newHead指向新的已反转的链表的表头;
- 指针currentHead指向当前原来的链表的表头;
- 最开始newHead指向原来链表的尾部“空”(NULL/None),currentHead指向原来链表的第一个元素。
例:
最开始:
NULL➡1(currentHead)➡2➡3➡4➡5➡NULL(newHead)
第1次操作:
1(newHead)➡NULL
2(currentHead)➡3➡4➡5➡NULL
- 新链表指针指向原链表第一个元素,第一个元素将成为新链表的最后一个元素,故其后指向NULL;当前链表指针头部往后移。
- 临时指针tmp暂存当前头部的下一个元素(后续将成为新的原链表头部)
- 在将当前头部变为新链表的头部前,更改当前头部的下一节点,链接新链表的头部(最开始是NULL)
第2次操作:
2(newHead)➡1➡NULL
3(currentHead)➡4➡5➡NULL
第3次操作:
3(newHead)➡2➡1➡NULL
4(currentHead)➡5➡NULL
第3次操作:
4(newHead)➡3➡2➡1➡NULL
5(currentHead)➡NULL
第4次操作:
5(newHead)➡4➡3➡2➡1➡NULL
currentHead == NULL(结束循环操作)
Python
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
if pHead == None or pHead.next == None:
return pHead
currentHead = pHead
newHead = None
while currentHead != None:
tmp = currentHead.next
currentHead.next = newHead
newHead = currentHead
currentHead = tmp
return newHead
C
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param pHead ListNode类
* @return ListNode类
*/
struct ListNode* ReverseList(struct ListNode* pHead ) {
// write code here
if(pHead == NULL || pHead->next == NULL){
return pHead;
}
struct ListNode* newHead = NULL;
struct ListNode* currentHead = pHead;
struct ListNode* tmp = NULL;
while(currentHead != NULL){
tmp = currentHead->next;
currentHead->next = newHead;
newHead = currentHead;
currentHead = tmp;
}
return newHead;
}