`
eriol
  • 浏览: 400564 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

链表逆序

阅读更多

链表逆序,即将原先的链表 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;
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics