将单向链表发转方向,头变尾,尾变头,将链表调个个儿。
思路:定义三个引用,pre为上一结点,cur为当前节点,nex为下一结点。
把cur的下一节点暂存到nex中,然后将cur的下一节点指向pre,再将pre指向cur,cur指向nex。只要cur不为空,就一直如此循环。直到cur为空,即最后一个节点的next结点为空。最后再把原链表的头节点变成了尾节点,所以要把它的next节点设置为null。
代码实现:
首先定义一个最简单的单链表数据结构。结构很简单,一个String类型的data,一个指向下一个节点的引用。
public class MyList {
private MyList next;
private String data;
public MyList getNext() {
return next;
}
public void setNext(MyList next) {
this.next = next;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public MyList(String data) {
this.data = data;
}
}
public class ConverMyList {
public static MyList conver(MyList myList) {
if (myList == null) {
System.out.println("error");
return myList;
}
MyList pre = myList;
MyList cur = myList.getNext();
MyList nex;
while (cur != null) {
nex = cur.getNext();
cur.setNext(pre);
pre = cur;
cur = nex;
}
myList.setNext(null);
return pre;
}
public static void main(String[] args) {
MyList myList = new MyList("a");
MyList myList2 = new MyList("b");
MyList myList3 = new MyList("c");
MyList myList4 = new MyList("d");
MyList myList5 = new MyList("e");
myList.setNext(myList2);
myList2.setNext(myList3);
myList3.setNext(myList4);
myList4.setNext(myList5);
System.out.println(JSON.toJSONString(myList));
//调用反转方法
MyList converList = conver(myList);
System.out.println(JSON.toJSONString(converList));
}
}
输出结果:
{"data":"a","next":{"data":"b","next":{"data":"c","next":{"data":"d","next":{"data":"e"}}}}}
{"data":"e","next":{"data":"d","next":{"data":"c","next":{"data":"b","next":{"data":"a"}}}}}