leetcode 206 反转链表
链表复习
单向链表
定义一个简单的链表
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
反转链表
此处借点大佬的博客,写的超级好,建议大家看一下
反转链表借鉴处
方法一
先对原链表做头删操作,再对新链表做头插
方法二
先对原链表做头删操作,再对新链表做头插
代码实现
public ListNode reverseList(ListNode head) {
if (head==null) return head;
ListNode temp=null;//中间变量
ListNode new_head=null;//新的头节点
while (head.next!=null){
temp=head;
head=head.next;
temp.next=new_head;
new_head=temp;
}
return new_head;
}