剑指offer 反转链表
问题描述
输入一个链表,反转链表后,输出新链表的表头。
C++代码实现
算法与剑指offer单链表的逆置相同
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode *p = nullptr, *q = pHead, *r = nullptr;
while(q)
{
r = q-> next;
q->next = p;
p = q;
q = r;
}
pHead = p;
return pHead;
}
};
python2代码实现
# -*- 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
pre = None
while pHead:
r = pHead.next
pHead.next = pre
pre = pHead
pHead = r
return pre
java代码实现
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode p = null, r = null;
while (head != null)
{
r = head.next;
head.next = p;
p = head;
head = r;
}
return p;
}
}