没怎么看懂书上说的3个指针,直接网上找的思路;
比如1->2->3->4这个链表,此时pHead指向1,那么:
1:用个指针pNext指向2,即pNext = pHead.next(pNext = 2)
2: 改下指针2的指针方向,pHead.next = pPre
3. 集体右移一位(改变当前元素的指向为preNode,并将preNode和nextNode均向右移动一位)
过程是:1->2->3->4;1<-2->3->4;1<-2<-3->4;1<-2<-3<-4;(注意pre,head,next三个指针的移动)
Python代码
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
if pHead == None:
return None
pPre = None
while pHead:
pNext = pHead.next
pHead.next = pPre
pPre,pHead = pHead,pNext
return pPre
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 pre = new ListNode();
while(head != null){
ListNode next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}
网上还给了一种递归的解法,ReverseList返回的是逆序链表,那么头结点就相当于逆序链表的最后一个节点,我们只要把头结点接在后面n-1个已经逆序的节点之后即可,别忘记把原有的pHead的next变为空;
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
if pHead == None:
return None
if pHead.next == None:
return pHead
pNext = pHead.next
newHead = self.ReverseList(pNext)
pNext.next = pHead
pHead.next = None
return newHead
java 代码:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null){return null;}
if(head.next == null){return head;}
ListNode pNext = head.next;
ListNode newHead = this.ReverseList(pNext);
pNext.next = head;
head.next = null;
return newHead;
}
}