剑指offer反转链表

没怎么看懂书上说的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;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值