您的位置:首页 > Web前端

剑指offer 14 反转链表

2016-03-29 16:36 483 查看


题目描述

输入一个链表,反转链表后,输出链表的所有元素。

思路

运用递归将首尾链表的值相交换。

由于java中的函数参数传递,对于普通类型,只是值传递,而对于自定义类,则是引用传递。

/*
public class ListNode {
int val;
ListNode next = null;

ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode temp;
public int mark=0;
public void find_ListNode(ListNode head){
if(head.next!=null)find_ListNode(head.next);
if(mark==1)return ;
int number_temp=temp.val;
temp.val=head.val;
head.val=number_temp;
if(temp==head||(temp.next==head)){mark=1;return ;}//如果两个指针都完全遍历一遍的话,那么元素的值是不会变的,如果遍历过程中相遇到,那么就结束掉。
if(temp.next!=null)temp=temp.next;
}
public ListNode ReverseList(ListNode head) {
if(head==null)return null;
temp=head;
ListNode test;
test=head;
find_ListNode(test);
return head;
}
}


第二个代码则是将链表的next指针反转,第一个的代码是讲listnode中的值(val)反转而已。

/*
public class ListNode {
int val;
ListNode next = null;

ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode pre=null;
ListNode next=null;
while(head!=null){
next=head.next;
head.next=pre;
pre=head;
head=next;
}
return pre;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: