问题描述: 给定一个单链表,将单链表进行反转。(即原单链表的头变为尾,尾变为头)
算法思路:
①可以定义cur用来遍历链表,pre指向cur的前驱节点,curnext指向cur的后继节点,newhead代表链表新的头。
②当cur不为空时遍历,可以发现反转链表cur的next域就是原单链表的前驱节点地址,就是pre。所以将pre赋值给cur的指针域,pre等于cur,最后cur向后走一步。当cur的next为空时,此时cur就是反转之后链表的新的头结点。
参考代码:
class ListNode{
public int data;
public ListNode next;
public ListNode(int data){
this.data=data;
this.next=null;
}
}//节点类
class MySignalList {
public ListNode head;
public MySignalList() {
this.head = null;
}
//尾插法
public void addLast(int data) {
ListNode node = new ListNode(data);
if (this.head == null) {
this.head = node;
} else {
ListNode cur = head;
while (cur.next != null) {
cur = cur.next;
}
cur.next = node;
}
}
//反转
public ListNode reverseList(){
ListNode cur=this.head;
ListNode newhead=null;
ListNode pre=null;
while(cur!=null){
ListNode curnext=cur.next;
if(curnext==null){
newhead=cur; //新的头节点
}
cur.next=pre; //将前驱赋值给当前节点的next域
pre=cur;
cur=curnext;
}
return newhead;
}
//打印单链表
public void display2(ListNode newHead){
ListNode cur=newHead;
while(cur!=null){
System.out.print(cur.data+" ");
cur=cur.next;
}
System.out.println();
}
}
public class Test {
public static void main(String[] args) {
MySignalList mySignalList1 = new MySignalList();
mySignalList1.addLast(1);
mySignalList1.addLast(4);
mySignalList1.addLast(6);
mySignalList1.addLast(7);
mySignalList1.addLast(56);
ListNode cur= mySignalList1.reverseList();
mySignalList1.display2(cur);
}
}
//打印结果
56 7 6 4 1