C++实现
ListNode* ReverseList(ListNode* pHead) {
ListNode* S,P=NULL;
while(pHead!=NULL){
S=pHead->next;
pHead->next=P;
P=pHead;
pHead=S;
}
return P;
}
想复杂了, 还在想怎么从后向前转移指针,或者整双链表(结果发现题目把结构定义好了),查了思路,直接把next指针掉个方向就好
Java实现
非递归
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode S,P=null;
while(head!=null) {
S=head.next;
head.next=P;
P=head;
head=S;
}
return P;
}
}
递归
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode pRever=ReverseList(head.next);
head.next.next=head;
head.next=null;
return pRever;
}
}
感觉很巧妙,其实没太清楚
重点看递归塞