思路如下图所示:
代码:
java代码:
Node reverse(Node head){
if(null == head || null == head.next ){//如果链表为空或只有一个元素
return head;
}
Node p = head.next;
head.next = null;//原来的头节点成了表尾
Node temp = null;
while(p != null){
temp = p.next;//将p.next保存
p.next = head;//逆置
head = p;//将逆置好的节点保存到head
p = temp;//进行下一轮遍历
}
return head;
}
C++:
ListNode* reverseList(ListNode* head) {
if(head==NULL || head->next==NULL)return head;
ListNode * cur = head->next;
head->next = NULL;//设置逆转后的链表尾节点指向null,否则会超时
ListNode * nxt = NULL;
while(cur!=NULL){
nxt = cur->next;
cur->next = head;
head = cur;
cur=nxt;
}
return head;
}