题意:反转一个单链表。
示例: 输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
方法一:双指针法
public class Fanzhuanlianbiao {
static class ListNode{
int val;//数据:节点数据
ListNode next;//对象,引用下一个数据对象
//链表类的构造方法
ListNode(int val){
this.val = val;
}
}
public void print (ListNode head){
while(head!=null){
System.out.print(head.val+" ");
head = head.next;
}
}
public ListNode reverseList(ListNode head){
//定义一个临时变量保存当前节点的下一个节点
ListNode temp;
//定义前驱节点
ListNode pre = null;
//定义当前节点
ListNode cur = head;
while(cur!=null){
//临时变量记录当前节点的下一个节点
temp=cur.next;
//当前节点指向前驱结点
cur.next = pre;
//前驱结点后移一位
pre = cur;
//当前节点后移一位
cur = temp;
}
return pre;
}
public static void main(String[] args) {
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
ListNode node5 = new ListNode(5);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
Fanzhuanlianbiao fanzhuanlianbiao = new Fanzhuanlianbiao();
ListNode node = node1;
fanzhuanlianbiao.print(node);
System.out.println();
ListNode res =fanzhuanlianbiao.reverseList(node1);
fanzhuanlianbiao.print(res);
}
}
输出结果:
12345
54321
方法二:递归法
思路跟双指针类似,注意递归的终点和递归的变量
//递归法
public ListNode reverseList(ListNode head){
return reverse(null,head);
}
private ListNode reverse(ListNode pre,ListNode cur){
//到达递归终点,返回pre
if (cur==null){
return pre;
}
//定义临时节点temp保存当前节点下一个节点
ListNode temp = null;
temp = cur.next;
//反转(当前节点指向前一个节点
cur.next = pre;
return reverse(cur,temp);
}
1206

被折叠的 条评论
为什么被折叠?



