//链表的结构
class LinkList {
String data;
LinkList next;
}
public class ReverseLinkList {
static LinkList hd = new LinkList();
public static void createLinkList(LinkList head) {
LinkList cur = head;
Scanner scanner = new Scanner(System.in);
String data;
System.out.println("输入单链表结点的值,输入#结束");
while (true) {
data = scanner.next();
if (data.equals("#")) {
cur.next = null;
break;
}
LinkList node = new LinkList();
node.data = data;
cur.next = node;
cur = cur.next;
}
}
//非递归逆置单链表
public static LinkList reverseList(LinkList head) {
if (head == null || head.next == null) {
return null;
}
LinkList pre = head;
LinkList cur = head.next;
while (cur != null) {
LinkList next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
head.next = null;
head = pre;
return head;
}
//递归逆置单链表
public static void recurReverseList(LinkList head, LinkList pCur) {
if (pCur == null || pCur.next == null) {
hd = pCur;
} else {
LinkList next = pCur.next;
recurReverseList(head, next);
next.next = pCur;
pCur.next = null;
}
}
//递归逆置单链表
public static LinkList recurReverseList1(LinkList head, LinkList pCur) {
if (pCur == null || pCur.next == null) {
hd = pCur;
return pCur;
} else {
LinkList next = recurReverseList1(hd, pCur.next);
next.next = pCur;
pCur.next = null;
return pCur;
}
}
反转单链表
最新推荐文章于 2019-03-18 15:26:38 发布