欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

链表逆序

程序员文章站 2022-03-11 21:45:39
...

链表逆序,即将原先的链表 a->b->c->d, 变为 d->c->b->a。需要使用三个指针来进行操作。

 

public int* reverse(int* head) {
	int* front = head;
	int* back = null;
	int* temp;
	
	while (front != null) {
		temp = font - > next;
		font -> next = back;
		back = font;
		font = temp;
	}
	
	return back;
}
 

 

如果要求链表两两逆序,例如 1->2->3->4 变成 2->1->4->3。该怎么呢?需要分情况处理链表长度为单数和偶数的情况。

 

public ListNode reverse(ListNode head) {
	if (head == null)
		return null;
	if (head.next == null)
		return head;

	ListNode back = head;
	ListNode front = head.next;
	ListNode temp;
	head = front;
	while (true) {
		temp = front.next;
		front.next = back;
		back.next = temp;
		if (temp == null || (temp != null && temp.next == null))
			break;
		else {
			front = temp.next;
			back.next = front;
			back = temp;
		}
	}
	return head;
}
 
相关标签: 链表