要求:给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null
- C++代码
/**
* Definition of ListNode
*
* class ListNode {
* public:
* int val;
* ListNode *next;
*
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/*
* @param head: n
* @return: The new head of reversed linked list.
*/
ListNode * reverse(ListNode * head) {
// write your code here
ListNode * now = head;//当前需要转化的节点
ListNode * pre = NULL;//now的前一个节点
ListNode * fot = NULL;//转化之后的最新的头结点(now的后一个节点)
while(now != NULL){
pre = now->next;//将前节点指向now节点的后一个节点
now->next = fot;//将当前节点反向指向前节点
fot = now;//将反向转好的节点赋值
now=pre;//now节点后移
}
return fot;
}
};
- Java代码
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/*
* @param head: n
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
// write your code here
ListNode now = head;
ListNode pre = null;
ListNode fot = null;
while(now != null){
pre = now.next;
now.next = fot;
fot = now;
now = pre;
}
return fot;
}
}