题目:定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
利用三个指针实现链表的反转
三个指针分别指向当前节点,当前节点的上一节点和下一节点,
将当前节点的指针下一节点指向上一节点,通过循环完成反转
package com.helan.c;
public class ReverseList {
public static class ListNode{
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
}
public static ListNode reverseList(ListNode head){
if(head==null){
return null;
}
ListNode reversedHead=head;
ListNode pNode=head;
ListNode preNode=null;
while(pNode!=null){
ListNode pNext=pNode.next;
if(pNode.next==null){
reversedHead=pNode;
}
pNode.next=preNode;
preNode=pNode;
pNode=pNext;
}
return reversedHead;
}
public static void printList(ListNode head){
while(head!=null){
System.out.print(head.val+"->");
head=head.next;
}
}
// 1->2->3->4->5->6
private void test01() {
ListNode n1 = new ListNode(1);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(3);
ListNode n4 = new ListNode(4);
ListNode n5 = new ListNode(5);
ListNode n6 = new ListNode(6);
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
n5.next = n6;
System.out.println("反转前:");
printList(n1);
ListNode node1=reverseList(n1);
System.out.println("");
System.out.println("反转后:");
printList(node1);
}
public static void main(String[] args) {
ReverseList a10=new ReverseList();
a10.test01();
System.out.println();
}
}
第二种方法运用递归,判断头节点不为空且不是只有一个节点,
保存当前节点的下一节点,打断当前节点的指针域,运用递归,改变指针域,前一个节点赋值到其下一个节点指针,返回
public static ListNode reverseList2(ListNode head) {
if (head == null||head.next==null) {
return head;
}
ListNode pNext=head.next;
head.next=null;
ListNode reversedHead=reverseList2(pNext);
pNext.next=head;
return reversedHead;
}