劍指offer第三天之反轉鏈表
輸入一個鏈表,反轉鏈表後,輸出新鏈表的表頭
java:
/*
data:2020517
author:魏振東
fun:輸入一個鏈表,反轉鏈表後,輸出新鏈表的表頭。
* */
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode r=null;
ListNode p=null;
//當前節點是head,p爲當前節點的前一節點,r爲當前節點的下一節點
while(head!=null)
{
r=head.next;
head.next=p;
//p向後移動一位,當前節點同樣向後移動一位
p=head;
head=r;
}
return p;
}
}
c++:
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode* r=NULL;
ListNode* node=pHead;
ListNode* p=NULL;
while(node!=NULL)
{
r=node->next;
node->next=p;
p=node;
node=r;
}
return p;
}
};
python:
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
t=None;
p=None;
while pHead!=None:
t = pHead.next
pHead.next = p
p=pHead
pHead =t
return p;