描述
数据范围: 0 ≤ n ≤ 1000
要求:空间复杂度 O(1)O(1) ,时间复杂度 O(n)O(n) 。
如当输入链表{1,2,3}时,
经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。
以上转换过程如下图所示:
C语言版
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* @param pHead ListNode类
* @return ListNode类
*/
struct ListNode* ReverseList(struct ListNode* pHead ) {
// write code here
struct ListNode *p,*q,*r;
p = pHead;
q=NULL;
while(p!=NULL){
r =q;
q=p;
p =p ->next;
q->next=r;
}
pHead =q;
return pHead;
}
JAVA版
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode newNode =null;
while(head !=null){
ListNode temp = head.next;
head.next = newNode;
newNode = head;
head = temp;
}
return newNode;
/*
if(head == null || head.next == null) return head;
ListNode node = ReverseList(head.next);
head.next.next=head;
head.next =null;
return node; */
}
}