leetcode :206.
需求:
反转链表
原链表:
graph LR A --> B --> C -->D -->null反转后:
graph RL D -->C --> B --> A -->null graph LR D-->C-->B-->A-->null双指针法:
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode ReverseList(ListNode head) {
//比如有 pre,1,2,3 在1 之前
ListNode pre = null;
var current = head;
while (current != null)
{
//先记录下下一个节点,不然一会找不到了
var temp = current.next;
//开始反转
current.next = pre;
pre = current;
current = temp;
}
//1-->2-->3-->null
//当current为null时 pre 刚好为最后一个节点3
return pre;
}
}
递归写法:
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode ReverseList(ListNode head) {
return reverse(head,null);
}
ListNode reverse(ListNode current,ListNode pre)
{
if(current == null)
return null;
var temp = current.next;
current.next = pre;
var result= reverse(temp,current) ;
return result ==null? current :result;
}
}
标签:current,ListNode,--,反转,next,链表,null,public
From: https://www.cnblogs.com/ChuanC/p/18219067