思路
先将链表的头部断开,然后把每个节点(第二个节点开始)向后的指针改成指向前一个元素
代码(前提是head必须不为null)
ListNode p1=head,p2=head.next;
p1.next=null;
while(p2!=null){
ListNode temp=p2.next;
p2.next=p1;
p1=p2;
p2=temp;
}
应用:力扣-206. 反转链表
代码
/**
* 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; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null){
return head;
}
ListNode p1=head,p2=head.next;
p1.next=null;
while(p2!=null){
ListNode temp=p2.next;
p2.next=p1;
p1=p2;
p2=temp;
}
return p1;
}
}