代码如下,核心的代码在于:
public static Node reverse(Node head) {
if(head==null) {
return null;
}
Node p = head;
Node q = head.next;
p.next=null; //这个必须的~~~,否则链表就成有环的了。
while(q!=null) {
Node temp = q.next;
q.next = p;
p = q;
q = temp;
}
return p;
}
整个程序如下所示:
package com.jy.list;
public class ReverseList {
public static void main(String[] args) {
Node head = add(null, "a");
add(head, "b");
add(head, "c");
add(head, "d");
add(head, "e");
print(head);
head = reverse(head);
print(head);
}
public static Node reverse(Node head) {
if(head==null) {
return null;
}
Node p = head;
Node q = head.next;
p.next=null; //这个必须的~~~,否则链表就成有环的了。
while(q!=null) {
Node temp = q.next;
q.next = p;
p = q;
q = temp;
}
return p;
}
public static Node add(Node head,String data) {
if(head==null) {
return new Node(data);
} else {
Node p = head;
while(p.next!=null) {
p = p.next;
}
p.next = new Node(data);
return head;
}
}
public static void print(Node head) {
if(head==null) {
System.out.println("null");
}else {
Node p = head;
while(p!=null) {
System.out.print(p.data+"\t");
p = p.next;
}
System.out.print("\n");
}
}
}
class Node {
public Node(String data2) {
this.data = data2;
}
public String toString() {
return data;
};
String data;
Node next;
}
分享到:
相关推荐
主要介绍了java 实现单链表逆转实例代码的相关资料,需要的朋友可以参考下
单链表逆转操作,在笔试中经常可见 1实现整体逆转 2.实现相邻元素逆转
使用C++描述的单链表处理程序源代码,可以实现单链表的逆转等操作。CodeBlocks下调试通过。
经典单链表的创建与单链表项的逆转,C++代码实现
一个C程序 实现了单链表的逆序 且复杂度为O n
C++ 实验 包含3个文件reverse.cpp CirHSLinkedList.h Node.h
单链表的逆转求和,根据输入,完成单链表的建立操作,然后实现单链表的逆转,输出逆转之后各几点的元素值,最后输出所有元素之和。
编写一个程序,使程序实现在单链表的某给定节点后插入新节点的算法,如找不到则插在尾部;并且能够查找给定节点并且删除;以及编写单链表逆转的算法。
c++实现单向链表逆转,c++实现单向链表逆转,c++实现单向链表逆转,c++实现单向链表逆转,c++实现单向链表逆转,
逆转线性单链表.doc逆转线性单链表.doc逆转线性单链表.doc逆转线性单链表.doc
3_单链表的逆转.cpp
template<class T> //定义在“LinkedChain.h” struct ChainNode //链表结点类的定义 { T data; //数据域 ChainNode<T> *link; //链指针域 ChainNode() //构造函数 { link=NULL;... ChainNode(T item,ChainNode...
详细描述了单链表逆转的思路及过程,并附源码
数据结构的常用代码,对单链表的逆置,常用的数据结构代码
该程序利用C语言编程,主要用到指针建立链表并将链表逆转
c++实现单链表的创建,逆转,以及找到寻找中间节点,用最小的空间找到倒数第m个节点
java 用递归实现字符串反转 java 用递归实现字符串反转
包括单链表的输入,输出和逆转后的输出。编译通过。
写一个算法,借助栈将一个带头结点的单链表倒置。类c算法