您的位置:首页 > 其它

反转链表

2018-03-28 15:56 176 查看
输入一个链表,反转链表后,输出链表的所有元素。

链表结构

public class ListNode {
int val;
ListNode next = null;

ListNode(int val) {
this.val = val;
}
}


算法思路:

1. 若链表空,直接返回头结点

2. 若链表不为空,设置pre, cur, next三个指针,设置cur的初值为head,其余两个指针初值为空。

3. 首先令next指向cur的下一元素,然后令cur.next指向pre,完成了cur指针的反转,最后更新pre和cur;

4. 重复上述过程,直至cur==null,此时pre的值,就是原链表的最后一个元素,即新链表的第一个元素,返回pre。

具体代码如下:

public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null){
return head;
}
ListNode pre = null;
ListNode cur = head;
ListNode next = null;
while(cur != null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: