题目:输入一个链表,反转链表后,输出新链表的表头。
思路一:一看到这个题目,想到的第一个方法就是递归,采用递归思路,遍历到终点,然后再返回的时候,来进行反转,最好在草稿上面画画,一下子就懂了。
代码一:
java
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null||head.next==null)
{
return head;
}
ListNode p=ReverseList(head.next);
head.next.next=head;
head.next=null;
return p;
}
}
js:
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function ReverseList(pHead)
{
if(pHead==null||pHead.next==null)
{
return pHead;
}
var p=ReverseList(pHead.next);
pHead.next.next=pHead;
pHead.next=null;
return p;
}
思路二:不采用递归思路,遍历一次,然后在遍历的过程中,进行反转,主要思想想清楚就好了。具体看代码。想清楚很简单。本题还有参用数组记录链表元素,但是代码比较麻烦。
代码二:
java
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode pre=null,next=null;
while(head!=null){
next=head.next;
head.next=pre;
pre=head;
head=next;;
}
return pre;
}
}
js
function ReverseList(pHead)
{
if(pHead==null||pHead.next==null)
return pHead;
var pre=null,next=null;
while(pHead!=null){
next=pHead.next;//下一个节点
pHead.next=pre;//把当前节点的Next指向pre
pre=pHead;//先前节点变成当前节点
pHead=next;//当前节点移动
}
return pre;
}