1.题目描述
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
2.题目解析
本题很简单,直接使用头插法把链表从第二个节点开始,依次插入到头部即可.
即第一步,设置一个节点等于head.next;
第二步 将 head.next =null;
然后我们遍历的时候,将cur!=null设置为遍历的条件
依次把cur进行链表的头插操作
注意: 要记录下cur的下一个节点,不然后面就找不到了.
即Listnode tmp = cur.next;
然后就依次头插即刻
3 代码书写
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
public ListNode reverseList(ListNode head) {
//如果头结点为空或者下一个为空,直接返回即刻
if(head == null || head.next == null){
return head;
}
ListNode cur = head.next;
head.next = null;
while(cur!=null){
//首先记录cur的下一个节点
ListNode tmp = cur.next;
cur.next = head;
head = cur;
cur = tmp;
}
return head;
}