实现单链表的反转

思想:如果是没有元素或一个元素,直接return 头结点
其他情况:
首先让p=head.next,然后让head结点的next为空。
然后依次取出p结点往head前插入即可。
- java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
//如果没有元素或只有一个元素
if(head==null||head.next==null){
return head;
}else{
ListNode p=head.next;
head.next=null;
while(p!=null){
ListNode pre=p;
p=p.next;
pre.next=head;
head=pre;
}
return head;
}
}
}
- javascript
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
//如果没有元素或只有一个元素
if(head===null||head.next===null){
return head;
}else{
let p=head.next;
head.next=null;
while(p!=null){
let pre=p;
p=p.next;
pre.next=head;
head=pre;
}
return head;
}
};