[算法学习]反转链表

问题描述: 输入一条链表,将链表反转后返回。

解法一:用递归

解法: 由于反转后头结点会成为尾结点,尾结点会成会头结点。所以从头结点开始反转前后结点关系。比较简单,所以这里直接贴出代码。


参考代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* 递归
* @param head
* @return
*/

public static ListNode reverseList1(ListNode head)
{

if(head==null)
{
return null;
}
ListNode parent=head.next;
if(parent==null)
{
return head;
}
head.next=null;
return reverseList1(head,parent);
}

/**
* 递归,绑定父子节点关系
* @param child
* @param parent
* @return
*/

private static ListNode reverseList1(ListNode child,ListNode parent)
{

if(parent==null)
{
return child;
}
ListNode last=parent.next;
parent.next=child;
return reverseList1(parent, last);
}

解法二:用循环,效率更高


参考代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* 反转链表,返回新的头节点
* @param head
* @return
*/

public static ListNode reverseList(ListNode head)
{

if(head==null)
{
return null;
}
ListNode pChild=head;
ListNode pParent=pChild.next;
ListNode pLast=null;
pChild.next=null;
while (pParent!=null)
{
// 绑定关系
pLast=pParent.next;
pParent.next=pChild;
// 设定关系
pChild=pParent;
pParent=pLast;
}
return pChild;
}