题目描述
翻转一个链表。
样例1
输入: 1->2->3->null
输出: 3->2->1->null
样例2
输入: 1->2->3->4->null
输出: 4->3->2->1->null
java题解
public class Solution {
public ListNode reverse(ListNode head) {
//prev表示前继节点
ListNode prev = null;
while (head != null) {
//temp记录下一个节点,head是当前节点
ListNode temp = head.next;
head.next = prev;
prev = head;
head = temp;
}
return prev;
}
}
C++题解
class Solution {
public:
ListNode *reverse(ListNode *head) {
//prev表示前继节点
ListNode *prev = NULL;
while (head != NULL) {
//temp记录下一个节点,head是当前节点
ListNode *temp = head->next;
head->next = prev;
prev = head;
head = temp;
}
return prev;
}
};
python题解
class Solution:
def reverse(self, head):
#curt表示前继节点
curt = None
while head != None:
#temp记录下一个节点,head是当前节点
temp = head.next
head.next = curt
curt = head
head = temp
return curt